Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify that template class is derived from a given class at compilation time?

I wonder, whether there is any elegant way (like this) for checking that template argument is derived from a given class? In general:

template<class A, class B>
class MyClass
{
    // shold give the compilation error if B is not derived from A
    // but should work if B inherits from A as private
}

the solution provided in another question works only when B inherits from A as public:

class B: public A

however, I would rather not have such constraint:

class A{};
class B : public A{};
class C : private A{};
class D;
MyClass<A,B> // works now
MyClass<A,C> // should be OK
MyClass<A,D> // only here I need a compile error

Thanks in advance!!!

like image 213
Serge Avatar asked Feb 24 '23 07:02

Serge


1 Answers

You can try something like I said here: C++: specifying a base class for a template parameter in a static assertion (either C++0x or BOOST_STATIC_ASSERT)

template<class A, class B> 
class MyClass 
{ 
  static_assert( boost::is_base_of<A,B>::value );
}
like image 152
Joel Falcou Avatar answered Feb 26 '23 19:02

Joel Falcou