在这段代码中,我希望将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:在函数'int ()‘中: source.cpp:22:5: error:解析模板参数列表中的错误 source.cpp:22:22: error:没有调用“print()”的匹配函数 source.cpp:22:22:注意:候选人是: source.cpp:11:6:注意:模板void () source.cpp:11:6:注意:模板参数演绎/替换失败: source.cpp:22:22:错误:模板参数2无效
如果我相反地将typedef更改为typedef int Type;,并将print调用更改为print<Foo, 3>();,那么它就能工作。通过查看错误消息,我尝试了几种方法,但是语法不正确。我也在这里搜索过,并发现了一些有用的帖子处理模板类,但没有处理模板函数。我试着用这些答案,但没有用。
请你帮我学习这个语法,或者向我解释我下一步应该做些什么来解决这个问题?
发布于 2013-02-04 15:57:55
这离你要找的东西很近吗?
#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);
}发布于 2013-02-04 16:00:26
x.y的地址在编译时是未知的。您可以将指向成员y的指针作为模板参数,但是必须在运行时传递对象实例的地址。
发布于 2013-02-04 15:59:45
当您将其更改为int时,它会工作,因为您允许将const作为模板参数传递。模板不允许将值作为参数传递,因为它们需要在编译时解析。
https://stackoverflow.com/questions/14690335
复制相似问题