C++中的模板断言?

ano*_*non 0 c++ inheritance templates

有没有办法定义模板

assertInheritsFrom<A, B>
Run Code Online (Sandbox Code Playgroud)

这样的

assertsInheritsFrom<A, B>
Run Code Online (Sandbox Code Playgroud)

编译当且仅当

class A : public B { ... } // struct A is okay too
Run Code Online (Sandbox Code Playgroud)

谢谢!

Geo*_*che 5

将静态断言与is_base_of<Base,Derived>Boost.TypeTraits 结合使用:

BOOST_STATIC_ASSERT(boost::is_base_of<B, A>::value);
Run Code Online (Sandbox Code Playgroud)

一个天真的实现(不处理整数类型,私有基类和歧义)可能如下所示:

template<class B, class D>
struct is_base_of {
    static yes test(const B&); // will be chosen if B is base of D
    static no  test(...);      // will be chosen otherwise
    static const D& helper();
    static const bool value = 
        sizeof(test(helper())) == sizeof(yes);
    // true if test(const B&) was chosen
};
Run Code Online (Sandbox Code Playgroud)