Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to typedef a std::array with a unspecified size?

I want to write some variables like

std::array<double, array_num> a;

where array_num is a const int representing the length of the array. But it's long and I want to create an alias for it:

typedef std::array<double, array_num> my_array;

Is it right? How can I use my_array like my_array<3>?

like image 615
yikouniao Avatar asked Dec 25 '15 13:12

yikouniao


1 Answers

What you need is an alias template:

template <size_t S>
using my_array = std::array<double, S>;

You cannot directly make a typedef template, see this post.

size_t is the type of the second template parameter std::array takes, not int.

Now that you know about using, you should be using that. It can do everything what typedef does, plus this. Also, you read it from left to right with a nice = sign as a delimiter, as opposed to typedef, which might hurt your eyes sometimes.


Let me add two more examples of use:

template <typename T>
using dozen = std::array<T, 12>;

And if you wanted to create an alias for std::array, such as it is, you'd need to mimic its template signature:

template <typename T, size_t S>
using my_array = std::array<T, S>;

- because this is not allowed:

using my_array = std::array;
like image 147
LogicStuff Avatar answered Nov 09 '22 13:11

LogicStuff