C ++ class template parameter must have a specific parent class

The specified MyClass with one template parameter

 template<typename T> class MyClass { //... }; 

and another class MySecondClass with two template parameters.

 template<typename T, typename U> class MySecondClass { //... }; 

What I would like to do is restrict MyClass only allow T , which is a derived type of MySecondClass . I already know that I need something like

 template<typename T, typename = std::enable_if<std::is_base_of<MySecondClass<?,?>, T>::value>> class MyClass { //... } 

I'm just not sure what to add in ? since I want to allow all possible MySecondClass .

+8
c ++ inheritance templates derived-class
source share
2 answers

You can use the template template parameter for the base template, and then check if T* can be converted to some Temp<Args...> :

 template <template <typename...> class Of, typename T> struct is_base_instantiation_of { template <typename... Args> static std::true_type test (Of<Args...>*); static std::false_type test (...); using type = decltype(test(std::declval<T*>())); static constexpr auto value = type::value; }; 

Live demo

+7
source share

You can use a custom tag to check if a type is derived from a template. Then use this trait inside static_assert :

 #include <type_traits> template <template <typename...> class T, typename U> struct is_derived_from_template { private: template <typename... Args> static decltype(static_cast<const T<Args...>&>(std::declval<U>()), std::true_type{}) test( const T<Args...>&); static std::false_type test(...); public: static constexpr bool value = decltype(test(std::declval<U>()))::value; }; template <typename T1, typename T2> struct MyParentClass { }; template<typename T> struct MyClass { static_assert(is_derived_from_template<MyParentClass, T>::value, "T must derive from MyParentClass"); }; struct DerivedFromMyParentClass : MyParentClass<int, float>{}; struct Foo{}; int main() { MyClass<DerivedFromMyParentClass> m; MyClass<Foo> f; } 

living example

+3
source share

All Articles