gpt4 book ai didi

c++ - 如何将 "int X::*"的内部 typedef 作为模板函数参数传递?

转载 作者:行者123 更新时间:2023-11-30 02:57:22 25 4
gpt4 key购买 nike

在这段代码中,我想传递 x.y 的地址作为模板参数 typename Name::Type leValue .

#include <iostream>
using std::cout;
using std::endl;

struct X {
X() : y(123) {}
const int y;
};

template<typename Name, typename Name::Type leValue>
void print() { cout << *leValue << endl; }

struct Foo {
typedef int X::* Type;
};


int main() {
X x;
print<Foo, &x.y>(); // What is the right syntax here?
}

但是,对于 gcc 4.7.2,我得到以下错误:

source.cpp: In function 'int main()':
source.cpp:22:5: error: parse error in template argument list
source.cpp:22:22: error: no matching function for call to 'print()'
source.cpp:22:22: note: candidate is:
source.cpp:11:6: note: template void print()
source.cpp:11:6: note: template argument deduction/substitution failed:
source.cpp:22:22: error: template argument 2 is invalid

如果我改为将 typedef 更改为 typedef int Type; , 以及对 print<Foo, 3>(); 的打印调用,然后就可以了。我通过查看错误消息尝试了几件事,但无法获得正确的语法。我也在这里搜索过,发现了一些处理模板类的有用帖子,但没有一个涉及模板函数。我尝试使用这些答案,但没有帮助。

你能帮我解决这个语法问题,或者向我解释一下接下来我应该尝试做什么来解决这个问题吗?

最佳答案

这是否接近您要查找的内容?

#include <iostream>
using std::cout;
using std::endl;

struct X {
X() : y(123) {}
const int y;
};

template<typename Name, typename Type, Type Name::*Member>
void print(Type& obj) { cout << obj.*Member << endl; }

int main() {
X x;
print<X, const int, &X::y>(x);
}

关于c++ - 如何将 "int X::*"的内部 typedef 作为模板函数参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14690335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com