Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a template member function? [duplicate]

Tags:

c++

templates

Possible Duplicate:
C++ template member function of template class called from template function

template<class T1>
class A 
{
public:
    template<class T0>
    void foo() const {}
};

template<class T0,class T1>
void bar( const A<T1>& b )
{
    b.foo<T0>();  // This throws " expected primary-expression before ‘>’ token"
}

I can change it to

b->A<T1>::template foo<T0>();

which compiles fine. However I can also change it to

b.A<T1>::template foo<T0>();

which compiles fine too. eh?

How does one correctly call the template member function in the sense of the original code?

like image 458
ritter Avatar asked Oct 01 '12 15:10

ritter


People also ask

How do you call a function in a template?

Defining a Function TemplateA function template starts with the keyword template followed by template parameter(s) inside <> which is followed by the function definition. In the above code, T is a template argument that accepts different data types ( int , float , etc.), and typename is a keyword.

Can a member function be a template?

Member functions can be function templates in several contexts. All functions of class templates are generic but are not referred to as member templates or member function templates. If these member functions take their own template arguments, they are considered to be member function templates.

Can a template function override?

You cannot define a virtual template method. override only works for virtual methods, and you can only override methods with the same signature.

What is a templated function?

Function templates. Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type. In C++ this can be achieved using template parameters.


2 Answers

Just found it:

According to C++'03 Standard 14.2/4:

When the name of a member template specialization appears after . or -> in a postfix-expression, or after nested-name-specifier in a qualified-id, and the postfix-expression or qualified-id explicitly depends on a template-parameter (14.6.2), the member template name must be prefixed by the keyword template. Otherwise the name is assumed to name a non-template.

Correct code is:

b.template foo<T0>();
like image 114
ritter Avatar answered Oct 11 '22 14:10

ritter


you can call the function this way:

b.template foo<T0>();
like image 21
Ninten Avatar answered Oct 11 '22 13:10

Ninten