class B {} template <class B> class A { }
现在想做个模板类A,但模板参数只能是B或B类的子类,怎么弄?
解决方案
40
class B {}; class BB : public B { }; class C { }; template<typename T> struct DerivedFromB { struct Small{char x;}; struct Big{char x[2];}; static Small match(B*); static Big match(...); enum {value = sizeof(match((T*)0)) == sizeof(Small)}; }; namespace support_static_assert { template <bool x> struct STATIC_ASSERTION_FAILURE; template <> struct STATIC_ASSERTION_FAILURE<true> { enum { value = 1 }; }; template<int x> struct static_assert_test{}; } #define STATIC_ASSERT(x) typedef support_static_assert::static_assert_test< \ sizeof(support_static_assert::STATIC_ASSERTION_FAILURE<(bool)(x) >) \ > static_assert_typedef template <class B> class A { STATIC_ASSERT(DerivedFromB<B>::value); }; int main() { A<B> orz; A<BB> orz1; //A<C> orz2; };