如何验证模板类是否在编译时从给定的类派生?

Ser*_*rge 4 c++ inheritance templates compiler-errors

我想知道,是否有任何优雅的方式(像这样)来检查模板参数是从给定的类派生的?一般来说:

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
}
Run Code Online (Sandbox Code Playgroud)

另一个问题中提供的解决方案仅在B继承自A作为公共时才起作用:

class B: public A
Run Code Online (Sandbox Code Playgroud)

但是,我宁愿没有这样的约束:

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
Run Code Online (Sandbox Code Playgroud)

提前致谢!!!

Joe*_*cou 7

您可以尝试我在此处所说的内容: C++: 在静态断言中指定模板参数的基类(C++ 0x或BOOST_STATIC_ASSERT)

template<class A, class B> 
class MyClass 
{ 
  static_assert( boost::is_base_of<A,B>::value );
}
Run Code Online (Sandbox Code Playgroud)