c++ - 当 Base 和 Derived 都使用 Derived 类型参数进行模板化时调用 Base 构造函数时出现编译器错误

标签 c++ c++11 templates inheritance

我很难理解为什么以下代码无法编译:

template <class T>
class Base {
    public:
        Base(int a){}
};
template <class T>
class Derived: public Base<T>  {
    public:
        Derived(int a): Base(a){}
};
int main(){}

在我的编译器(gcc 5.4.0 with C++ 11)上输出错误信息

error: class 'Derived<T>' does not have any field named 'Base'
         Derived(int a): Base(a){}

我看到这有点类似于 Template base constructor call in member initialization list error ,虽然那个测试用例实际上为我编译而这个没有:主要区别似乎是 BaseDerived 使用相同的类型参数。此外,如果我显式添加类型参数或为 base 提供显式范围,它编译得很好,如

template <class T>
class Base {
    public:
        Base(int a){}
};

template <class T>
class Derived: public Base<T>  {
    public:
        Derived(int a): Derived::Base(a){}
};

int main(){}

这是怎么回事?我是否误解了何时可以使用注入(inject)的类名?

最佳答案

注入(inject)的类名Base是类 Base 的成员,并且由于基类是依赖的,因此在非限定名称查找期间不会搜索其范围。因此,使用名称 Base只会找到类模板,而不是 Base<T> 的注入(inject)类名.这就是为什么你必须写 Base<T> .

Derived::Base之所以有效,是因为它会导致名称查找推迟到 Derived被实例化。

关于c++ - 当 Base 和 Derived 都使用 Derived 类型参数进行模板化时调用 Base 构造函数时出现编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56211130/

相关文章:

c# - 无法在Unity 5中执行extern c函数

c++ - 仅在基于范围的循环中迭代奇数(偶数)元素

c++ - 在 C++ 中更改模板模板参数

C++ 继承和成员函数指针

C++11 简化了调用同一模板函数的不同特化的模板函数的语法

c++ - boost 互斥锁

c++11:在 VS2015 中使用 initializer_list 分配全局 STL "map<string, string>"崩溃

c++ - 我怎样才能使这个模板方法更优雅? (或 : less explicit template parameters required)

c++ - 使用通用函数指针参数化函数模板的巧妙方法

html - 用响应式模板中的文本框替换下拉菜单