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>
?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With