【发布时间】:2017-09-28 11:09:45
【问题描述】:
我很难理解为什么以下代码无法编译:
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(){}
在我的编译器(带有 C++ 11 的 gcc 5.4.0)上,这会输出错误消息
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,尽管该测试用例实际上为我编译,而这个却没有:主要区别似乎是Base 和Derived 使用相同的类型参数。此外,如果我显式添加类型参数或为 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(){}
发生了什么事?什么时候可以使用注入的类名是我误解了吗?
【问题讨论】:
-
为什么不派生:Base
(a)? -
请注意it works as is with MSVC,因为 MSVC 的名称查找与 GCC 不同。尽管措辞不同,但 Clang 会发出与 GCC 相同的错误。
标签: c++ c++11 templates inheritance