4

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!!!

Community
  • 1
  • 1
Serge
  • 1,027
  • 14
  • 21

2 Answers2

7

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 );
}
Community
  • 1
  • 1
Joel Falcou
  • 6,247
  • 1
  • 17
  • 34
1

Inheriting privately from anything is an implementation detail.

During refactoring and code analysis I would be much happier if such detection would not be possible for functionality outside...

maxim1000
  • 6,297
  • 1
  • 23
  • 19