在此代码中,我想传递x.y
的地址作为模板参数typename Name::Type leValue
。如何传递“int X :: *”的内部typedef作为模板函数参数?
#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>();
,那么它的工作原理。我通过查看错误消息尝试了几件事情,但无法获得正确的语法。我也在这里进行了搜索,发现了一些有用的帖子处理模板类,但没有处理模板函数。我试着使用这些答案,但它没有帮助。
你能帮我解释一下这个语法,或者向我解释我应该尝试下一步做什么来解决这个问题?
'x.y'只是一个'const int'。 – aschepler
'&X :: y' – Xeo
@Xeo我试过了,它没有工作。 错误:无法将模板参数'&X :: y'转换为'Foo :: Type {aka int X :: *}'' –