(注意:这个问题是关于不必指定元素数量并且仍然允许直接初始化嵌套类型。)
这个问题 https://stackoverflow.com/questions/6111565/now-that-we-have-stdarray-what-uses-are-left-for-c-style-arrays讨论 C 数组的剩余用途,例如int arr[20];
. On 他的回答 https://stackoverflow.com/questions/6111565/now-that-we-have-stdarray-what-uses-are-left-for-c-style-arrays/6113104#6113104,@James Kanze展示了C数组最后的据点之一,它独特的初始化特性:
int arr[] = { 1, 3, 3, 7, 0, 4, 2, 0, 3, 1, 4, 1, 5, 9 };
我们不必指定元素的数量,万岁!现在使用 C++11 函数对其进行迭代std::begin
and std::end
from <iterator>
(或者你自己的变体 https://stackoverflow.com/questions/5897319/how-to-use-stdsort-to-sort-a-array-in-c/5897358#5897358)并且您甚至不需要考虑它的大小。
现在,有没有任何(可能是 TMP)方法可以实现相同的效果std::array
?允许使用宏使其看起来更好。 :)
??? std_array = { "here", "be", "elements" };
Edit:中间版本,根据各种答案编译而成,如下所示:
#include <array>
#include <utility>
template<class T, class... Tail, class Elem = typename std::decay<T>::type>
std::array<Elem,1+sizeof...(Tail)> make_array(T&& head, Tail&&... values)
{
return { std::forward<T>(head), std::forward<Tail>(values)... };
}
// in code
auto std_array = make_array(1,2,3,4,5);
并采用了各种很酷的 C++11 东西:
- 可变参数模板
sizeof...
- 右值引用
- 完美转发
-
std::array
, 当然
- 统一初始化
- 省略返回类型并进行统一初始化
- 类型推断(
auto
)
可以找到一个例子here http://ideone.com/fsfT0.
However正如@Johannes 在@Xaade 的答案的评论中指出的那样,您无法使用这样的函数初始化嵌套类型。例子:
struct A{ int a; int b; };
// C syntax
A arr[] = { {1,2}, {3,4} };
// using std::array
??? std_array = { {1,2}, {3,4} };
此外,初始值设定项的数量仅限于实现支持的函数和模板参数的数量。