2013-02-04 28 views
1

在此代码中,我想传递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>();,那么它的工作原理。我通过查看错误消息尝试了几件事情,但无法获得正确的语法。我也在这里进行了搜索,发现了一些有用的帖子处理模板类,但没有处理模板函数。我试着使用这些答案,但它没有帮助。

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

+0

'x.y'只是一个'const int'。 – aschepler

+0

'&X :: y' – Xeo

+0

@Xeo我试过了,它没有工作。 错误:无法将模板参数'&X :: y'转换为'Foo :: Type {aka int X :: *}'' –

回答

2

这是接近你在找什么?

#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); 
} 
+0

感谢您对此问题的帮助。但是,内部typedef是必不可少的部分。我正在处理一个客户端的代码,我在这个问题中粘贴的代码是一个匿名化和简化版本。 –

+1

注意,当Name是一个模板参数时,如果你想要的只是嵌套类型,而不是特定的成员指针,你可以在定义中使用typedef Name :: Type作为类型。你不需要另一个模板参数。 – aschepler

0

它在您将其更改为int时起作用,因为您允许将const int作为模板参数传递。模板不会让您将值作为参数传递,因为它们需要在编译时解析。

1

编译时未知地址x.y。您可以使用指向成员y的指针作为模板参数,但是,您必须在运行时传递对象实例的地址。

+0

我明白你的意思了。我分享的代码是客户端代码的匿名和简化版本。也许我没有正确描述它。让我再次考虑一遍。 –

相关问题