How to test whether class B is derived from template family of classes

Try this:

#include <type_traits>

template <typename T, template <typename> class Tmpl>  // #1 see note
struct is_derived
{
    typedef char yes[1];
    typedef char no[2];

    static no & test(...);

    template <typename U>
    static yes & test(Tmpl<U> const &);

    static bool const value = sizeof(test(std::declval<T>())) == sizeof(yes);
};

Usage:

#include <iostream>

template<class T> struct X {};

struct A : X<int> {};

int main()
{
    std::cout << is_derived<A, X>::value << std::endl;
    std::cout << is_derived<int, X>::value << std::endl;
}

Note: In the line marked #1, you could also make your trait accept any template that has at least one, but possibly more type arguments by writint:

template <typename, typename...> class Tmpl

Leave a Comment