提及模板基类时,到处都需要模板参数吗? [英] Are template arguments required everywhere when mentioning a template base class?

查看:123
本文介绍了提及模板基类时,到处都需要模板参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的模板;

Here's a simple template;

template <class T>
class tt {
    private:
        T  x;
    public:
        tt() {x=0;};
        Add(T p) {x += p;};
};

...然后是它的子类;

... and then a subclass of it;

class cc : public tt<int> {

    public:
        cc() : tt() {};

};

这在VC中可以很好地进行编译,但是在C ++ Builder(XE)中却出​​现E2102错误,因此不能很好地编译. C ++ Builder编译器需要在cc类的构造函数上使用以下语法进行编译;

This compiles fine in VC, but not in C++ Builder (XE) where it gives a E2102 error. The C++ Builder compiler needs the following syntax on the constructor of the cc class to compile;

cc() : tt<int>() {};

实际上,每次在cc类中提到tt模板时,C ++ Builder编译器都需要重复模板参数.

In fact, the C++ Builder compiler needs the template parameters repeated every time the tt template are mentioned within the cc class.

标准C ++规范是否指定了需要不断重复模板参数的需求,或者C ++ Builder编译器是否错误?

Does the standard C++ specification specify the need for constantly repeating the template parameters or is the C++ Builder compiler wrong?

推荐答案

C ++ Builder在这里是错误的.之所以能够在构造函数的成员初始化程序列表中使用祖先的名称,与注入的类名的概念有关.

C++ Builder is wrong here. The reason why you should be able to use the ancestor's name in the constructor's member initializer list has to do with the concept of injected class name.

定义类时,编译器将类的名称插入该类并使其引用自身.注入的名称使您可以使用类的名称,而无需在类内部使用模板参数.

When you define a class, the compiler inserts the name of the class into that class and makes it refer to itself. This injected name is what allows you to use the name of the class without template arguments inside the class.

template <class T>
struct tt {
    // The compiler behaves as if there was the following.
    // typedef tt<T> tt;
};

在成员初始化器列表中使用名称tt时,将查找此注入的名称.

This injected name is what gets looked up when you use the name tt in the member initializer list.

(为了便于记录,clang接受不带模板参数的代码段.)

(For the record, clang accepts the snippet without the template argument.)

奖金::如果您将cc定义为具有模板参数T的类模板,并且祖先依赖于T,则名称tt不会在cc构造函数的成员初始化程序列表的上下文.

Bonus: had you defined cc as a class template with the template parameter T and the ancestor was dependent on T, the name tt would not be found in the context of cc's constructor's member initializer list.

template <class T>
class cc : tt<T> {
    cc()
        : tt<T>() /* You must use <T> here. */
    {
    }
};

这篇关于提及模板基类时,到处都需要模板参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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