开发者

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;
}


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜