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

后端 未结 10 920
难免孤独
难免孤独 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:58

    Create an array maker type.

    It overloads operator, to generate an expression template chaining each element to the previous via references.

    Add a finish free function that takes the array maker and generates an array directly from the chain of references.

    The syntax should look something like this:

    auto arr = finish( make_array->* 1,2,3,4,5 );
    

    It does not permit {} based construction, as only operator= does. If you are willing to use = we can get it to work:

    auto arr = finish( make_array= {1}={2}={3}={4}={5} );
    

    or

    auto arr = finish( make_array[{1}][{2}[]{3}][{4}][{5}] );
    

    None of these look like good solutions.

    Using variardics limits you to your compiler-imposed limit on number of varargs and blocks recursive use of {} for substructures.

    In the end, there really isn't a good solution.

    What I do is I write my code so it consumes both T[] and std::array data agnostically -- it doesn't care which I feed it. Sometimes this means my forwarding code has to carefully turn [] arrays into std::arrays transparently.

提交回复
热议问题