Museful
Museful

Reputation: 6959

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?

Upvotes: 0

Views: 49

Answers (2)

Barry
Barry

Reputation: 303087

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

Upvotes: 4

Jarod42
Jarod42

Reputation: 217283

You can create a traits for that:

template <typename T>
struct is_foo : std::false_type {};

template <typename T>
struct is_foo<Foo<T>> : std::true_type {};

Upvotes: 2

Related Questions