Is there a way to define a template
assertInheritsFrom<A, B>
such that
assertsInheritsFrom<A, B>
compiles if and only if
class A : public B { ... } // struct A is okay too
Thanks!
Is there a way to define a template
assertInheritsFrom<A, B>
such that
assertsInheritsFrom<A, B>
compiles if and only if
class A : public B { ... } // struct A is okay too
Thanks!
Combine static asserts with is_base_of<Base,Derived>
from Boost.TypeTraits:
BOOST_STATIC_ASSERT(boost::is_base_of<B, A>::value);
A naive implementation (not taking care of integral types, private base classes and ambiguities) might look like the following:
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
};
You can read this section Detecting convertibility and inheritance at compile time from Alexandrescu's book.
EDIT: One more link for the same: http://www.ddj.com/cpp/184403750 Look for Detecting convertibility and inheritance
You might also want to read this entry from Bjarne Stroustrup's C++ FAQ: Why can't I define constraints for my template parameters? (The answer is that you can, and he provides an example how to implement a Derived_from
constraint.)