下面给出的示例代码不是用g ++编译的.但它正在开发视觉工作室.是否可以在g ++中的模板类中使用模板成员函数
class Impl
{
public:
template<class I>
void Foo(I* i)
{
}
};
template<class C>
class D
{
public:
C c;
void Bar()
{
int t = 0;
c.Foo<int>(&t);
}
};
int main()
{
D<Impl> d;
d.Bar();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
因为有问题的语句取决于模板参数,所以C在实例化之前不允许编译器进行内省.你必须告诉它你的意思是一个功能模板:
c.template Foo<int>(&t);
Run Code Online (Sandbox Code Playgroud)
如果你没有放在template那里,声明是模棱两可的.为了理解,请想象以下内容C:
class C { const int Foo = 5; };
...
c.Foo<int>(&t);
Run Code Online (Sandbox Code Playgroud)
它将编译器视为将a与a const int进行比较int,并将其结果与以下某些地址进行比较&t:(c.Foo<int) > &t.
然而,真正的解决方案是在函数调用中省略显式模板参数,并且只做:
c.Foo(&t);
Run Code Online (Sandbox Code Playgroud)
即使在这种情况C具有非模板成员函数的情况下,这也是正确的Foo(int).通常,尽可能少地编写模板代码(但不能少于).