C++ class template of specific baseclass

Let's say I have the classes:

class Base{};

class A: public Base{
    int i;
};

class B:public Base{
    bool b;
};

And now I want to define a templated class:

template < typename T1, typename T2 >
class BasePair{
    T1 first;
    T2 second;
};

But I want to define it such that only decendants of class Base can be used as templateparameters.

How can I do that?


Solution 1:

C++11 introduces <type_traits>

template <typename T1, typename T2>
class BasePair{
static_assert(std::is_base_of<Base, T1>::value, "T1 must derive from Base");
static_assert(std::is_base_of<Base, T2>::value, "T2 must derive from Base");

    T1 first;
    T2 second;
};

Solution 2:

More exactly:

class B {};
class D1 : public B {};
class D2 : public B {};
class U {};

template <class X, class Y> class P {
    X x;
    Y y;
public:
    P() {
        (void)static_cast<B*>((X*)0);
        (void)static_cast<B*>((Y*)0);
    }
};

int main() {
    P<D1, D2> ok;
    P<U, U> nok; //error
}

Solution 3:

C++ doesn’t yet allow this directly. You can realize it indirectly by using a STATIC_ASSERT and type checking inside the class:

template < typename T1, typename T2 >
class BasePair{
    BOOST_STATIC_ASSERT(boost::is_base_of<Base, T1>);
    BOOST_STATIC_ASSERT(boost::is_base_of<Base, T2>);
    T1 first;
    T2 second;
};

Solution 4:

This was a great question! While researching this via this link, I came up with the following, which admittedly isn't much different than the provided solution there. Learn something everyday...check!

#include <iostream>
#include <string>
#include <boost/static_assert.hpp>

using namespace std;

template<typename D, typename B>
class IsDerivedFrom
{
  class No { };
  class Yes { No no[3]; };

  static Yes Test(B*); // declared, but not defined
  static No Test(...); // declared, but not defined

public:
  enum { IsDerived = sizeof(Test(static_cast<D*>(0))) == sizeof(Yes) };
};


class Base
{
public:
    virtual ~Base() {};
};

class A : public Base
{
    int i;
};

class B : public Base
{
    bool b;
};

class C
{
    string z;
};


template <class T1, class T2>
class BasePair
{
public:
    BasePair(T1 first, T2 second)
        :m_first(first),
         m_second(second)
    {
        typedef IsDerivedFrom<T1, Base> testFirst;
        typedef IsDerivedFrom<T2, Base> testSecond;

        // Compile time check do...
        BOOST_STATIC_ASSERT(testFirst::IsDerived == true);
        BOOST_STATIC_ASSERT(testSecond::IsDerived == true);

        // For runtime check do..
        if (!testFirst::IsDerived)
            cout << "\tFirst is NOT Derived!\n";
        if (!testSecond::IsDerived)
            cout << "\tSecond is NOT derived!\n";

    }

private:
    T1 m_first;
    T2 m_second;
};


int main(int argc, char *argv[])
{
    A a;
    B b;
    C c;

    cout << "Creating GOOD pair\n";
    BasePair<A, B> good(a, b);

    cout << "Creating BAD pair\n";
    BasePair<C, B> bad(c, b);
    return 1;
}