Calaf
Calaf

Reputation: 10837

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

Why is it that in the code below template<typename T> struct Child : public Parent requires a definition, whereas template<typename T> struct Orphan does not require one (but the presence of one does not hurt)?

#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 specialization\n";
    }
};

// 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 specialization\n";
    }
};

int main()
{
    Orphan<int> orphan;
    Child<int> child;
}

Upvotes: 0

Views: 166

Answers (2)

UncleBens
UncleBens

Reputation: 41351

template<typename T>
struct Orphan;

This is a perfectly normal forward declaration.

I suppose the language simply forbids forward declarations containing declaration of the parent. Such a syntax doesn't exist.

So it doesn't have much to do with templates. You can't do the following either

class Base {};

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

And in your case, you could forward declare Child as usual

template <class T>
class Child;

Now the only question is: when we are trying to create an instance of the class, do we still only have a forward declaration or do we have a complete type.

Upvotes: 1

Mark B
Mark B

Reputation: 96281

In order to inherit you always need a full class definition.

In order to specialize all the compiler needs to know is the name of the template class. In this case, any use of the specialization would work when the full definition is required. Any use of the non-int-specialized version would only be treated as if a forward declaration were available.

Upvotes: 1

Related Questions