How to emulate C array initialization “int arr[] = { e1, e2, e3, … }” behaviour with std::array?

后端 未结 10 928
难免孤独
难免孤独 2020-11-22 17:23

(Note: This question is about not having to specify the number of elements and still allow nested types to be directly initialized.)
This question discu

10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 17:57

    Using trailing return syntax make_array can be further simplified

    #include 
    #include 
    #include 
    
    template 
    auto make_array(T&&... t)
      -> std::array, sizeof...(t)>
    {
      return {std::forward(t)...};
    }
    
    int main()
    {
      auto arr = make_array(1, 2, 3, 4, 5);
      return 0;
    }
    

    Unfortunatelly for aggregate classes it requires explicit type specification

    /*
    struct Foo
    {
      int a, b;
    }; */
    
    auto arr = make_array(Foo{1, 2}, Foo{3, 4}, Foo{5, 6});
    

    In fact this make_array implementation is listed in sizeof... operator


    c++17 version

    Thanks to template argument deduction for class templates proposal we can use deduction guides to get rid of make_array helper

    #include 
    
    namespace std
    {
    template  array(T... t)
      -> array, sizeof...(t)>;
    }
    
    int main()
    {
      std::array a{1, 2, 3, 4};
      return 0; 
    }
    

    Compiled with -std=c++1z flag under x86-64 gcc 7.0

提交回复
热议问题