从模板参数派生的子类

huangapple go评论67阅读模式
英文:

Derived class from template parameter

问题

Multiple definitions of Derived class is not allowed, so the following is a compile time error.

多次定义`Derived`类是不允许的,因此以下是编译时错误。

Sameways, why isn't the following, a compile time error?
Wouldn't there be 2 versions of Derived class, one inheriting from A1 while the other from A2?

同样地,为什么以下代码不是编译时错误?
难道不会有两个版本的`Derived`类,一个继承自`A1`,另一个继承自`A2`?

class A1
{    };

class A2
{    };

template<class T>
class Derived: public T
{    };
    
int main()
{
        Derived<A1> *ptr1 = new Derived<A1>;
        Derived<A2> *ptr2 = new Derived<A2>;    
}
英文:

Multiple definitions of Derived class is not allowed, so the following is a compile time error.

class A1
{    };

class A2
{    };

class Derived: public A1
{    };
class Derived: public A2
{    };

Sameways, why isn't the following, a compile time error?
Wouldn't there be 2 versions of Derived class, one inheriting from A1 while the other from A2?

class A1
{    };

class A2
{    };

template&lt;class T&gt;
class Derived: public T
{    };
    
int main()
{
        Derived&lt;A1&gt; *ptr1 = new Derived&lt;A1&gt;;
        Derived&lt;A2&gt; *ptr2 = new Derived&lt;A2&gt;;    
}

答案1

得分: 4

以下是您要翻译的内容:

不会有两个继承自A1A2Derived类,而只会有一个名为Derived&lt;A1&gt;Derived&lt;A2&gt;的类。您传递给模板参数的数据会成为类的一部分。声明Derived&lt;A1&gt;并将A1传递给模板参数T,您会实例化一个类模板。

我认为这里解释得更清楚:

> 模板实例化 涉及生成一个特定模板参数组合的具体类或函数(实例)。

并且不会有Derived类存在。正如max66在评论中指出的那样,Derived不是一个类,而是一个类模板,如果没有实例化,它将无法单独编译。

英文:

There would be not two Derived classed, inherited from A1 and A2, but literally one class Derived&lt;A1&gt; and Derived&lt;A2&gt;. The data you pass to template argument, becomes part of the class. Delcaring Derived&lt;A1&gt; and passing A1 to the template argument T you instantiate a class template.

I think here is explained better:

> Template instantiation involves generating a concrete class or
> function (instance) for a particular combination of template
> arguments.

And there would be no Derived class at all. As max66 pointed out in comment, Derived is not a class, but a class template, which will not be compiled alone, without instantiation.

huangapple
  • 本文由 发表于 2020年1月3日 17:43:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/59576226.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定