在完全专门化中,为什么继承使前向声明(没有定义)不再足够?

In a full specialization, why does inheritance make a forward declaration (without definition) no longer sufficient?

本文关键字:定义 不再 声明 专门化 为什么 继承      更新时间:2023-10-16

为什么在下面的代码中template<typename T> struct Child : public Parent需要定义,而template<typename T> struct Orphan不需要定义(但是存在一个没有伤害)?

#include <iostream>
struct Parent {};
// A definition is necessary.
template<typename T>
struct Child : public Parent
{};
template<>
struct Child<int> : public Parent
{
    Child() {
        std::cout << "Child<int>::Child: full specializationn";
    }
};
// No definition is necessary (but the presence of one doesn't hurt).
template<typename T>
struct Orphan;
template<>
struct Orphan<int>
{
    Orphan() {
        std::cout << "Orphan<int>::Orphan: full specializationn";
    }
};
int main()
{
    Orphan<int> orphan;
    Child<int> child;
}
template<typename T>
struct Orphan;

这是一个完全正常的前向声明。

我想语言只是禁止包含父类声明的前向声明。这样的语法不存在。

所以它和模板没有太大关系。

class Base {};
class Derived: public Base;  //forward declaration of Derived

在您的情况下,您可以像往常一样转发声明Child

template <class T>
class Child;

现在唯一的问题是:当我们试图创建类的实例时,我们是否仍然只有一个前向声明,还是我们有一个完整的类型。

为了继承你的总是需要一个完整的类定义。

为了特化,编译器只需要知道模板类的名称。在这种情况下,当需要完整的定义时,任何专门化的使用都可以工作。任何非int专门化版本的使用都将被视为前向声明可用。