Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling template function of template base class [duplicate]

Possible Duplicate:
Where and why do I have to put the “template” and “typename” keywords?

Here's the code:

template<typename T>
class base
{
public:
    virtual ~base();

    template<typename F>
    void foo()
    {
        std::cout << "base::foo<F>()" << std::endl;
    }
};

template<typename T>
class derived : public base<T>
{
public:
    void bar()
    {
        this->foo<int>(); // Compile error
    } 
};

And, when running:

derived<bool> d;
d.bar();

I get the following errors:

error: expected primary-expression before ‘int’
error: expected ‘;’ before ‘int’

I'm aware of non-dependent names and 2-phase look-ups. But, when the function itself is a template function (foo<>() function in my code), I tried all workarounds only to fail.

like image 899
Daniel K. Avatar asked Feb 15 '12 08:02

Daniel K.


People also ask

What is template function and template class?

A template allows us to create a family of classes or family of functions to handle different data types. Template classes and functions eliminate the code duplication of different data types and thus makes the development easier and faster. Multiple parameters can be used in both class and function template.

Can we override template function in C++?

You may overload a function template either by a non-template function or by another function template. The function call f(1, 2) could match the argument types of both the template function and the non-template function.

What is difference between class template and function template in C++?

For normal code, you would use a class template when you want to create a class that is parameterised by a type, and a function template when you want to create a function that can operate on many different types.

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.


1 Answers

foo is a dependent name, so the first-phase lookup assumes that it's a variable unless you use the typename or template keywords to specify otherwise. In this case, you want:

this->template foo<int>();

See this question if you want all the gory details.

like image 58
Mike Seymour Avatar answered Sep 20 '22 12:09

Mike Seymour