anon
anon

Reputation: 42577

Template assertion in C++?

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!

Upvotes: 0

Views: 318

Answers (3)

Naveen
Naveen

Reputation: 73433

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

Upvotes: 2

Georg Fritzsche
Georg Fritzsche

Reputation: 98964

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

Upvotes: 5

jamesdlin
jamesdlin

Reputation: 89926

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

Upvotes: 1

Related Questions