Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call to template member function failing to compile

Tags:

c++

templates

I have a problem with a piece of code of the following form:

template<class Type>
class Class1 {
public:
    template<class TypeName1> TypeName1* method1() const {return 0;}
};

struct Type1{};
struct Type2{};

class Class2 {
public:
   template<typename TypeName1, typename TypeName2>
   int method2() {
       Class1<TypeName2> c;
       c.method1<TypeName1>();
       return 0;
   }

   int method1() {
       return method2<Type1, Type2>();
   }
};

int
main() {
   Class2 c;
   return c.method1();
}

When compiled with compiler at codepad:

http://codepad.org/ZR1Std4k

I get the following error:

t.cpp: In member function 'int Class2::method2()': Line 15: error: expected primary-expression before '>' token compilation terminated due to -Wfatal-errors.

The offending line is the invocation of the template member function:

c.method1<TypeName1>();
like image 453
Andreas Brinck Avatar asked Feb 11 '13 12:02

Andreas Brinck


1 Answers

You should use the template keyword when you are invoking a member function template and you have a dependent name, or method1 will be parsed as a member variable of c and < as a "less than" symbol:

c.template method1<TypeName1>();

As @DrewDormann correctly points out, the reason why the template keyword is required is that a specialization of the Class1 class template could exist for the particular type argument provided, where method1 is defined as a member variable rather than a function template. Thus, the compiler must be explicitly instructed to parse method1 as the name of a function template if this is not the case.

like image 93
Andy Prowl Avatar answered Oct 17 '22 23:10

Andy Prowl