实现一个std ::阵列像一个C ++ 11 initializer_list容器 [英] Implementing a std::array-like container with a C++11 initializer_list

查看:135
本文介绍了实现一个std ::阵列像一个C ++ 11 initializer_list容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的std ::阵列的唯一和国际海事组织非常不方便需要注意的是,它不能从初始化列表推断其大小如内置的C数组,它的大小必须为模板进行传递。

是否有可能实现一个std ::阵列状的容器(大约瘦包装一个内建C数组)以 C ++ 11 initializer_list <? / p>

我问,因为,不同的std ::阵列,它会自动推断从初始化列表的数组这是很多更方便的大小。例如:

  // il_array是假想的容器
//自动从initalizer名单推断其大小
il_array&LT; INT&GT; myArr,该= {2,4,6,7,8};

我们也想提供一个构造函数,如果没有提供一个初始化列表来指定大小。例如:

  //构造大小为10的一个固定大小的数组
il_array&LT; INT&GT; myarr2(10);

这也会使容器如其他标准集装箱更加一致向量,双端队列和列表。

据我所知这是不可能的包裹C-阵列例如ŧelems [尺寸],必须有固定的大小和initializer_list的大小()成员函数不是恒定的。

另外,我想知道是否有可能使用的是可变参数模板来实现这样的容器,虽然从我读过,我不认为这是可能的。


解决方案

我觉得你的运气了这里。的std ::阵列的很大的优点是,它是一个POD和可以静态初始化。

如果你有一个构造函数接受一个std :: initializer_list的容器,它必须复制值(除非它仅仅是一个恒定的参考初始化,这是不是非常有用)。

The only and imo very inconvenient caveat of std::array is that it can't deduce its size from the initializer list like built-in C arrays, it's size must be passed as a template.

Is it possible to implement a std::array-like container (a thin wrapper around a built-in C array) with a C++11 initializer_list?

I ask because, unlike std::array, it would automatically deduce the size of the array from the initializer list which is a lot more convenient. For example:

// il_array is the hypothetical container
// automatically deduces its size from the initalizer list 
il_array <int> myarr = {2, 4, 6, 7, 8}; 

We would also want to provide a constructor to specify the size if an initializer list was not provided. For example:

// construct a fixed size array of size 10
il_array <int> myarr2 (10); 

This would also make the container more consistent with the other standard containers e.g. vector, deque and list.

To the best of my knowledge it isn't possible as the wrapped C-array e.g. T elems [size], must have constant size and initializer_list's size() member function isn't constant.

Also, I was wondering if was possible to implement such a container using a variadic template although from what I've read I don't think it's possible.

解决方案

I think you are out of luck here. The great advantage of std::array is that it is a POD and can be statically initialized.

If you have a container with a constructor taking a std::initializer_list, it would have to copy the values (unless it is just a constant reference to the initializer, which isn't very useful).

这篇关于实现一个std ::阵列像一个C ++ 11 initializer_list容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆