calling template function of template base class

Daniel K. picture Daniel K. · Feb 15, 2012 · Viewed 23.5k times · Source

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.

Answer

Mike Seymour picture Mike Seymour · Feb 15, 2012

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.