当使用派生类型参数对Base和Derived进行模板化时,调用Base构造函数时发生编译器错误 [英] Compiler Error When Calling Base Constructor when both Base and Derived are Templated With Derived Type Parameter

查看:65
本文介绍了当使用派生类型参数对Base和Derived进行模板化时,调用Base构造函数时发生编译器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力理解为什么以下代码无法编译:

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(){}

在我的编译器上(带有C ++ 11的gcc 5.4.0 ),这会输出错误消息

On my compiler (gcc 5.4.0 with C++ 11) this outputs the error message

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

我看到这有点相似到成员初始化列表错误中的模板基础构造函数调用 ,尽管该测试用例实际上是为我编译的,而我却没有:主要区别似乎是 Base Derived 使用相同的类型参数。另外,如果我显式添加类型参数或为base提供显式范围,则编译效果很好,例如

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. Additionally, it compiles fine if I explicitly add the type parameters or I give an explicit scope for base, as in

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?

推荐答案

注入的类名 Base Base 类的成员,并且由于基类是从属的,因此在不限定名称的查找过程中不会搜索其范围。因此,使用名称 Base 将仅找到类模板,而不会找到注入的 Base< T> 的类名。 。这就是为什么必须编写 Base< T> 的原因。

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. As such, using the name Base will only find the class template, not the injected class name of Base<T>. That is why you must write Base<T>.

Derived :: Base 之所以起作用,是因为它会导致名称查找被延迟,直到实例化

Derived::Base works because it causes name lookup to be postponed until Derived is instantiated.

这篇关于当使用派生类型参数对Base和Derived进行模板化时,调用Base构造函数时发生编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆