英文:
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<class T>
class Derived: public T
{ };
int main()
{
Derived<A1> *ptr1 = new Derived<A1>;
Derived<A2> *ptr2 = new Derived<A2>;
}
答案1
得分: 4
以下是您要翻译的内容:
不会有两个继承自A1
和A2
的Derived
类,而只会有一个名为Derived<A1>
和Derived<A2>
的类。您传递给模板参数的数据会成为类的一部分。声明Derived<A1>
并将A1
传递给模板参数T
,您会实例化一个类模板。
我认为这里解释得更清楚:
> 模板实例化 涉及生成一个特定模板参数组合的具体类或函数(实例)。
并且不会有Derived
类存在。正如max66在评论中指出的那样,Derived
不是一个类,而是一个类模板,如果没有实例化,它将无法单独编译。
英文:
There would be not two Derived
classed, inherited from A1
and A2
, but literally one class Derived<A1>
and Derived<A2>
. The data you pass to template argument, becomes part of the class. Delcaring Derived<A1>
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论