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/43712270/

相关文章:

c++ - 我们如何将 Phoenix Singleton 放在同一个地址? C++

c++ - 避免重复 const 和非 const 版本的 getter?

c++ - 连接字符和字符串文字

c++ - -Werror 是否会干扰模板正确性和/或 SFINAE?

c++ - 在Boost::Hana中使用BOOST_HANA_DEFINE_STRUCT定义具有40个以上字段的结构

python - c++运行python代码以导入自定义模块

c++ - 在 C++ 中创建自定义类的 native 数组

c++ - 结构值在 C++ 中未正确打印

.net - 在 .NET 中生成简单报告的模板引擎

java - EJB3 应用程序的具有简单 URL 的最佳 View 层