Search code examples
c++templatesgenericstype-traits

is_base_of of generic type


I'm trying to assert that template parameter would be derived from some base class. But base class is generic and in the context of assertion there is no difference between any specialization types. How can I assert, that template parameter were derived from generic of any specialized type?

I'm trying to write it as

base_generic:

template<typename T> struct base_generic{};

derived_generic:

template<typename T> struct derived_generic : public base_generic<T>{};

class with assertion:

template<typename Tsource, typename Tderived_generic> 
struct encoder {
static_assert(std::is_base_of<base_generic<typename>, Tderived_generic>::value);
};

This code compiles, but assertion fails


Solution

  • From commentary of @PiotrSkotnicki

    template <template <typename...> class Base, typename Derived>
    struct is_base_of_template
    {
        using U = typename std::remove_cv<Derived>::type;
    
        template <typename... Args>
        static std::true_type test(Base<Args...>*);
    
        static std::false_type test(void*);
    
        using type = decltype(test(std::declval<U*>()));
    };
    
    template <template <typename...> class Base, typename Derived>
    using is_base_of_template_t = typename is_base_of_template<Base, Derived>::type;
    

    This solution works fine, example.