views:

102

answers:

3

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!

+6  A: 

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
};
Georg Fritzsche
can you please explain how this works? (i.e. how is_base_of is implemented, it's a bit beyond my comprehension)
anon
It's an open-source library: http://www.boost.org/doc/libs/1_41_0/libs/type_traits/doc/html/boost_typetraits/reference/is_base_of.html
Travis Gockel
Travis, that's the same link from the answer, and it doesn't actually explain how it works. Inspecting the code won't necessarily explain it, either. Sometimes prose helps. But probably not an amount that would fit in Stack Overflow comments. Anon, if you've attempted to read the code and still don't understand, please post a new question about it. (Note there's some effort to explain it in Boost's is_base_and_derived.hpp, with some links.)
Rob Kennedy
+2  A: 

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

Naveen
Could you please provide a summary here? Google will only serve a book so often, and then it blocks everyone else for a while.
Rob Kennedy
Implemented it; works flawlessly.
anon
+1  A: 

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

jamesdlin