0

I have to following example code. In this code I have two template classes each with a template function. One of the classes has an object of the other class and in the template function it calls the template of the other class.

template<typename T>
class A{
public:
A(T a): a(a){}

template< typename V> V foo(){
    return this->a;
}

private:
T a;
};

template<typename T>
class B{
public:
B( A<T> a): a(a){}

template<typename V>V foo2(){
     return this->a.foo<V>();
}

private:
A<T> a;
};

int
main()
{

    A<int> a(5);
    double  aTest = a.foo<double>();
    B<int> b(a);
    double c = b.foo2< double >();
}

I need to provide the template element after the function call, because automatic type deduction does not work for functions, were only the return type depends on the template parameter. This works for aTest. But when I add the next two lines I get the following compiler error:

build/main.cpp: In member function 'V B<T>::foo2()':
build/main.cpp:32:23: error: expected primary-expression before '>' token
return this->a.foo<V>();
                   ^
build/main.cpp:32:25: error: expected primary-expression before ')' token
return this->a.foo<V>();
Thorsten
  • 333
  • 1
  • 5
  • 20
  • [Clang is really clear.](http://coliru.stacked-crooked.com/a/5577f94bc88beadf) http://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords – chris Jun 29 '14 at 04:32
  • Thanks for the link. Really good explaination. I was aware of the typename use, but not of the template. – Thorsten Jun 29 '14 at 04:38

1 Answers1

1

You need to use:

template<typename V>V foo2(){
     return this->a.template foo<V>();
}

To find gory details of why you need to use template in the call to a.foo, please take a look at this SO answer: https://stackoverflow.com/a/613132/434551

Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270