janekb04
janekb04

Reputation: 4945

How to "overload" templated alias declaration in C++?

I want to create a type alias array_t. It should work for both bounded and unbounded arrays. I can declare it for each case separately like this:

// Type of an unbounded array of `T`
template <typename T>
using array_t = T[];
// Type of an array of `T` of size `Size`
template <typename T, size_t Size>
using array_t = T[Size];

The problem is that both cannot be declared at the same time. I think that the solution could be to use some kind of template specialization, but I am not sure how to use it in this case.

Upvotes: 2

Views: 1173

Answers (1)

Antoni
Antoni

Reputation: 186

According to cppreference (https://en.cppreference.com/w/cpp/language/type_alias)

It is not possible to partially or explicitly specialize an alias template.

However, it is possible to use non-type template parameter pack so we can use the following trick:

template <class T, size_t... Sizes>
struct array_t_helper 
{ };

template <class T, size_t Size>
struct array_t_helper<T, Size>
{
    using t = T[Size];
};

template <class T>
struct array_t_helper<T>
{
    using t = T[];
};

template <typename T, size_t... Sizes>
using array_t = typename array_t_helper<T, Sizes...>::t;

Upvotes: 6

Related Questions