开发者

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

开发者 https://www.devze.com 2023-03-03 10:17 出处:网络
I wonder, whether there is any elegant way (like this) for checking that template argument is derived from a given class?

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开发者_如何学Python 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!!!


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 );
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消