[英]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. 其中
array_num
是一个表示数组长度的const int
。 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>
? 如何像
my_array<3>
一样使用my_array
?
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 . 您无法直接创建
typedef
模板,请参阅此帖子 。
size_t
is the type of the second template parameter std::array
takes, not int
. size_t
是第二个模板参数std::array
size_t
的类型,而不是int
。
Now that you know about using
, you should be using that. 既然您知道
using
,那么您应该使用它。 It can do everything what typedef
does, plus this. 它可以完成
typedef
所做的一切,加上这个。 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. 另外,你用一个漂亮的
=
符号作为分隔符从左到右阅读它,而不是typedef
,这有时会伤害你的眼睛。
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: 如果你想为
std::array
创建一个别名,比如它,你需要模仿它的模板签名:
template <typename T, size_t S>
using my_array = std::array<T, S>;
- because this is not allowed: - 因为这是不允许的:
using my_array = std::array;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.