[英]Compiler Error When Calling Base Constructor when both Base and Derived are Templated With Derived Type Parameter
I am struggling to understand why the following code does not compile: 我正在努力理解为什么以下代码无法编译:
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(){}
On my compiler (gcc 5.4.0 with C++ 11) this outputs the error message 在我的编译器(带有C ++ 11的gcc 5.4.0)上,这将输出错误消息
error: class 'Derived<T>' does not have any field named 'Base'
Derived(int a): Base(a){}
I see that this is somewhat similar to Template base constructor call in member initialization list error , though that test case actually compiles for me while this one does not: The main difference seems to be that both Base
and Derived
use the same type parameter. 我看到这有点类似于成员初始化列表错误中的Template base构造函数调用 ,尽管该测试用例实际上是为我编译的,而这个却没有:主要区别似乎是
Base
和Derived
使用相同的类型参数。 Additionally, it compiles fine if I explicitly add the type parameters or I give an explicit scope for base, as in 另外,如果我显式添加类型参数或为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(){}
What's going on? 这是怎么回事? Am I misunderstanding when injected class names may be used?
当使用注入的类名时,我是否会误解?
The injected class name Base
is a member of the class Base
, and since the base class is dependent, its scope is not searched during unqualified name lookup. 注入的类名
Base
是类的一个成员Base
,并且由于基类是相关的,其范围并不限定名称查找期间搜索。 As such, using the name Base
will only find the class template, not the injected class name of Base<T>
. 因此,使用名称
Base
只会找到类模板,而不是注入的Base<T>
类名。 That is why you must write Base<T>
. 这就是为什么必须编写
Base<T>
。
Derived::Base
works because it causes name lookup to be postponed until Derived
is instantiated. Derived::Base
之所以起作用,是因为它导致名称查找被推迟到实例化Derived
之前。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.