lightxbulb lightxbulb - 1 year ago 53
C++ Question

C++ template declaration with inheritance list

Is it possible to declare a templated class in C++ along with the classes it inherits from? Basically I want to give the compiler a hint, that my templated class will always inherit another at declaration time.
Maybe some code will clear up why this is a problem for me:

template<typename T>
class GrandparentClass
{
public:
T grandparentMember;
};

//this needs to be only a declaration, since I do not want classes of ParentClass with random T
template<typename T>
class ParentClass : public GrandparentClass<T>
{

};

// this does not work:
//template<typename T>
//class ParentClass : public GrandparentClass<T>;

// this does not either, because then the child class cannot access the variable from the grandparent class
//template<typename T>
//class ParentClass;

template<>
class ParentClass<int> : public GrandparentClass<int>
{
public:
ParentClass()
{
grandparentMember = 5;
}
};

template <typename T>
class ChildClass : public ParentClass<T>
{
public:
void foo()
{
std::cout << grandparentMember << "\n";
}
};


Also, I cannot use C++ 11.

Answer Source

A class declaration is only really useful for non-value variable declarations, like pointers and references. You can't access the class members or even instantiate it, though. Even if you knew that a declared class inherits from some other one, you still wouldn't necessarily be able to utilize that information in any way.

As such, it's only important for the compiler to know what the class inherits from once it learns its full definition.


After clarification in comments: if you want to prevent instantiation of a class template with some types, its definition is the place to do it. A simple static_assert inside the class body will do the trick; Boost.StaticAssert or older SFINAE tricks will do the job for pre-C++11 code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download