c++ - 调用模板基类的模板函数

标签 c++ templates dependent-name

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

代码如下:

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
    } 
};

并且,在运行时:

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

我收到以下错误:

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

我知道non-dependent names and 2-phase look-ups .但是,当函数本身是模板函数(我的代码中的 foo<>() 函数)时,我尝试了所有变通方法都失败了。

最佳答案

foo 是一个依赖名称,因此第一阶段查找假定它是一个变量,除非您使用 typenametemplate 关键字另有说明。在这种情况下,您需要:

this->template foo<int>();

this question如果你想要所有血淋淋的细节。

关于c++ - 调用模板基类的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9289859/

相关文章:

c++ - 如何在不创建构造函数的情况下使用私有(private)/ protected 成员初始化 POD 结构?

C# vs C++ 三元运算符

c++ - 这是 MSVC 中依赖名称解析的错误吗?

c++ - 如果一个函数类型只依赖于它自己的模板参数,它是否依赖于它?

c++ - 为什么我没有收到字节数组中的数据?

c++ - 如何从 boost::geometry::model::polygon 获取多边形?

c++ - 专门用于任意类型 vector 的模板

c++ - 如何声明作为类中任何类型对象的数据成员

c++ - 在派生类中绑定(bind)非静态模板化成员函数