Array class that will accept an braced-init-list and deduce length

  • A+

This has been asked before, but I'm curious to see if anything has changed in newer C++ standards. Any current or future standard is acceptable.

Q: Is there anyway to create an Array class that can be initialized with a braced-init-list without having to manually specify the array length, and without a 'make_array' function.

template<class T, size_t N> struct Array {     T items[N]; };  Array<int> foo = { 1, 2, 3 }; 

Since initializer_list is not templated on the size, a constructor using it won't do the job. Deduction guides in C++17 nearly work, but you have to omit the type parameter and all items must have exactly the same type

Array foo = { 1, 2, 3 }; // Works Array<int> foo = { 1, 2, 3 }; // Doesn't work Array foo = { 1.0, 2.0, 3.0f }; //Doesn't work 

A constructor that takes a c-array doesn't appear to work because an initializer_list won't convert to a c-array.

Is the braced-init-list to T[N] that happens in int foo[] = { 1, 2, 3 }; purely compiler magic that can't be replicated in code?

EDIT: The spirit of this question is about the exact syntax above. No make_array, no extra template argument, explicit item type, no double braces. If a trivial Array requires a bunch of modern C++ tomfoolery and still can't manage to support standard syntax then it's just a bad engineering tradeoff in my opinion.


You can work around the need for all the types in the list to be the same by using an explicit deduction guide:

template <class... T> Array(T&&... t) -> Array<std::common_type_t<T...>, sizeof...(T)>;  Array foo = { 1.0, 2.0, 3.0f }; // Deduces Array<double,3u> 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: