如何使用常规构造函数模式初始化C 11标准容器?

前端之家收集整理的这篇文章主要介绍了如何使用常规构造函数模式初始化C 11标准容器?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
下面的长显式初始化列表是否可以被生成它的某个模板替换?
  1. std::array<Foo,n_foos> foos = {{
  2. {0,bar},{1,{2,{3,{4,{5,{6,{7,}};

现在这里这段代码的工作原理只是因为我们有constexpr int n_foos = 8.如何对任意和大的n_foos进行此操作?

解决方法

以下解决方案使用C 14 std :: index_sequence和std :: make_index_sequence(其中 can be easily implemented in C++11 program):
  1. template <std::size_t... indices>
  2. constexpr std::array<Foo,sizeof...(indices)>
  3. CreateArrayOfFoo(const Bar& bar,std::index_sequence<indices...>)
  4. {
  5. return {{{indices,bar}...}};
  6. }
  7.  
  8. template <std::size_t N>
  9. constexpr std::array<Foo,N> CreateArrayOfFoo(const Bar& bar)
  10. {
  11. return CreateArrayOfFoo(bar,std::make_index_sequence<N>());
  12. }
  13.  
  14. // ...
  15.  
  16. constexpr std::size_t n_foos = 8;
  17. constexpr auto foos = CreateArrayOfFoo<n_foos>(bar);

live example.

猜你在找的C&C++相关文章