问题
sample code given below is not compiled in g++. but it's working on visual studio. is it possible to use Template member function inside template class in 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;
}
回答1:
Because the statement in question depends on a template parameter, the compiler is not allowed to introspect C
until instantiation. You must tell it that you mean a function template:
c.template Foo<int>(&t);
If you don't put template
there, the statement is ambiguous. For understanding, imagine the following C
:
class C { const int Foo = 5; };
...
c.Foo<int>(&t);
It looks to the compiler as if you compare a const int
to an int
, and comparing the result of that to some adress of &t
: (c.Foo<int) > &t
.
The real solution however is to omit the explicit template argument in the function call, and just do:
c.Foo(&t);
This is correct even in the case where such a C
has a non-template member function Foo(int)
. Generally, write template code with as few assumptions as possible (but not less).
回答2:
Foo()
is a template-dependent name, so you need to put template
in front of the invocation:
template<class C>
void D<C>::Bar()
{
int t = 0;
c.template Foo(&t);
}
来源:https://stackoverflow.com/questions/10187082/why-does-this-code-not-compile-in-g