Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking Inheritance with templates in C++

I've a class which is a wrapper class(serves as a common interface) around another class implementing the functionality required. So my code looks like this.

template<typename ImplemenationClass> class WrapperClass {
// the code goes here
}

Now, how do I make sure that ImplementationClass can be derived from a set of classes only, similar to java's generics

<? extends BaseClass>

syntax?

like image 247
JSN Avatar asked Feb 04 '26 22:02

JSN


1 Answers

It's verbose, but you can do it like this:

#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_base_of.hpp>

struct base {};

template <typename ImplementationClass, class Enable = void>
class WrapperClass;

template <typename ImplementationClass>
class WrapperClass<ImplementationClass,
      typename boost::enable_if<
        boost::is_base_of<base,ImplementationClass> >::type>
{};

struct derived : base {};
struct not_derived {};

int main() {
    WrapperClass<derived> x;

    // Compile error here:
    WrapperClass<not_derived> y;
}

This requires a compiler with good support for the standard (most recent compilers should be fine but old versions of Visual C++ won't be). For more information, see the Boost.Enable_If documentation.

As Ferruccio said, a simpler but less powerful implementation:

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

struct base {};

template <typename ImplementationClass>
class WrapperClass
{
    BOOST_STATIC_ASSERT((
        boost::is_base_of<base, ImplementationClass>::value));
};
like image 121
Daniel James Avatar answered Feb 06 '26 10:02

Daniel James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!