Search code examples
c++c++14sfinaetype-traitsenable-if

Type trait test if template parameter is some instantiation of another template


Suppose in the following code the intention is to allow T in Bar<T> to be a Foo<U> for any U.

template<typename U>
class Foo { };

template<typename T, typename = std::enable_if_t< /*T is Foo<U> for any U*/>>
class Bar {
    // ...
};

Is there something I replace /*T is Foo<U> for any U*/ with?


Solution

  • You can write a general trait to match for any specialization:

    template <typename T, template <typename...> class Z>
    struct is_specialization_of : std::false_type { };
    
    template <typename... Args, template <typename....> class Z>
    struct is_specialization_of<Z<Args...>, Z> : std::true_type { };
    

    Which in your specific case would be:

    is_specialization_of<T, Foo>::value // <== T is some kind of Foo