Does the standard library have a way to check the equality of two templated types' base template type?

Having trouble coming up with the correct terminology to search for this adequately, but does the standard library have something to test for the same base template type?

template <typename T>
struct foo {};

template <typename T>
struct bar {};

static_assert(std::is_same_base_type<foo<int>, foo<float>>::value == 1);
static_assert(std::is_same_base_type<foo<int>, bar<int>>::value == 0);

Upvotes: 1

Views: 79

Answers (1)

max66
max66

Reputation: 66210

In the standard library?

No, as far I know.

But is trivial to write it.

template <typename, typename>
struct is_same_template : public std::false_type
 { };

template <template <typename> class C, typename T, typename U>
struct is_same_template<C<T>, C<U>> : public std::true_type
 { };

So you can write

static_assert( true == is_same_template<foo<int>, foo<float>>::value, "!" ) ;
static_assert( false == is_same_template<foo<int>, bar<int>>::value, "!" );

The problem of this solution is that the specialization works only for template-template bases receiving only one template type parameter.

You can improve it, for bases (template-template arguments) receiving a variadic list of arguments

template <template <typename...> class C,
          typename ... Ts, typename ... Us>
struct is_same_template<C<Ts...>, C<Us...>> : public std::true_type
 { };

but this doesn't works to check, by examples, std::array

static_assert( true == is_same_template<std::array<int, 3u>,
                                        std::array<float, 5u>>::value, "!" ) ;

For std::array you have to add another specialization

template <template <typename, std::size_t> class C,
          typename T1, std::size_t S1, typename T2, std::size_t S2>
struct is_same_template<C<T1, S1>, C<T2, S2>> : public std::true_type
 { };

Unfortunately there are innumerable possible template-template signatures so you have to add innumerable is_same_template specializations.

This is the reason (I suppose) there isn't a standard library type-traits.

Upvotes: 5

Related Questions