calling template function of template base class [duplicate]

本小妞迷上赌 提交于 2019-11-27 14:42:19

问题


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.


回答1:


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.




回答2:


You should do it like this :

template<typename T>
class derived : public base<T>
{
public:
    void bar()
    {
        base<T>::template foo<int>();
    } 
};

Here is full compilable example :

#include <iostream>

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()
    {
        base<T>::template foo<int>(); // Compile error
    }
};

int main()
{
  derived< int > a;
  a.bar();
}


来源:https://stackoverflow.com/questions/9289859/calling-template-function-of-template-base-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!