且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么C ++要求我在初始化列表中重复基类的模板参数?

更新时间:2023-11-12 17:04:34

仅当Derived是模板且基础类型取决于其模板参数时,才需要这样做.

You only need to do that when Derived is a template and the type of the base depends on its template parameters.

例如,编译如下:

template <typename T>
class Derived : public Base<int, false>
{
public:
    Derived(const T& t) : Base(t) {}
};

据我所知,这里(在成员初始值设定项列表中)Base实际上是Base<...>的注入类名称,它像其他所有内容一样从其继承.

As far as I know, here (in member initializer list) Base is actually the injected-class-name of Base<...>, inherited from it like everything else.

如果基础的类型确实取决于模板参数,则其继承的注入类名称将变得不可访问(至少直接访问),就像从其继承的任何其他成员一样.

And if the type of the base does depend on the template parameters, its inherited injected-class-name becomes inaccessible (at least directly), just like any other member inherited from it.

对于成员变量/函数,您需要添加this->来访问它,但是对于类型成员,则需要Derived:::

For a member variable/function, you'd add this-> to access it, but for a type member you need Derived:::

template <typename T>
class Derived : public Base<T, false>
{
public:
    Derived(const T& t) : Derived::Base(t) {}
};