2

Is there any way to make a template only work with child classes of a base class? Something like this:

template<BaseClass T>
class FooBar
{
    // ...
};
Paul Manta
  • 30,618
  • 31
  • 128
  • 208

3 Answers3

5

Either use a static assert from your favourite C++ library (such as this boost example), or put a call in the constructor (or other code which will always be generated when the code is used) to a do-nothing function taking a BaseClass type, for example:

template<class T>
class FooBar
{
public:
    FooBar () {
        Check(static_cast<T*>(0));
    }

private:
    void Check ( BaseClasse* ) {} 
};

(not tested)

Pete Kirkham
  • 48,893
  • 5
  • 92
  • 171
2

Not directly, but you can test it in the constructor using Boost:

#include <boost/type_traits/is_base_of.hpp>
#include <boost/static_assert.hpp>

template<class T>
class FooBar{
  FooBar(){
    BOOST_STATIC_ASSERT(boost::is_base_of<BaseClass,T>::value);
  }
};

Or if you don't want a static assert, something like this is also nice sometimes:

typedef char ERROR_T_must_be_derived_from_BaseClass[boost::is_base_of<BaseClass,T>::value ? 1 : -1];

Since whoever compiles your code will be brought to this line and has a "readable" error message.

Xeo
  • 129,499
  • 52
  • 291
  • 397
0

There are ways to make it work with a static assert. See Boost.StaticAssert

CashCow
  • 30,981
  • 5
  • 61
  • 92