Why this code does not compile in g ++

the below code example does not compile in g ++. but he works at a visual studio. Is it possible to use a member function of a template inside a 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; } 
+7
source share
2 answers

Since the operator in question depends on the template parameter, the compiler is not allowed to introspect C until an instance is created. You should say that you mean a function template:

 c.template Foo<int>(&t); 

If you do not 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 at the compiler, as if you were comparing const int with int and comparing the result of this with some address &t : (c.Foo<int) > &t .

The real solution , however, is to omit the explicit template argument in the function call, and simply do:

 c.Foo(&t); 

This is correct even when such C has a non-template member function Foo(int) . As a rule, write the template code with the most possible assumptions (but not less).

+9
source

Foo() is a template-dependent name, so you need to put template before the call:

 template<class C> void D<C>::Bar() { int t = 0; c.template Foo(&t); } 
+4
source

All Articles