Search code examples
c++templatesdependent-name

calling template function of template base class


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.


Solution

  • 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.