How to create std::array with initialization list without providing size directly

Neil Kirk picture Neil Kirk · Oct 14, 2014 · Viewed 21.7k times · Source

How can I make a3 compile?

int main()
{
    int a1[] = { 1, 2, 3 };
    std::array<int, 3> a2 = { 1, 2, 3 };
    std::array<int> a3 = { 1, 2, 3 };
}

It's very inconvenient, and brittle, to hard-code the size of the array when using an initialization list, especially long ones. Is there any work around? I hope so otherwise I'm disappointed because I hate C arrays and std::array is supposed to be their replacement.

Answer

Shafik Yaghmour picture Shafik Yaghmour · Oct 14, 2014

There is currently no way to do this without rolling your own make_array, there is a proposal for this N3824: make_array which has the following scope:

LWG 851 intended to provide a replacement syntax to

array<T, N> a = { E1, E2, ... };

, so the following

auto a = make_array(42u, 3.14);

is well-formed (with additional static_casts applied inside) because

array<double, 2> = { 42u, 3.14 };

is well-formed.

This paper intends to provide a set of std::array creation interfaces which are comprehensive from both tuple’s point of view and array’s point of view, so narrowing is just naturally banned. See more details driven by this direction in Design Decisions.

It also includes a sample implementation, which is rather long so copying here is impractical but Konrad Rudolph has a simplified version here which is consistent with the sample implementation above:

template <typename... T>
constexpr auto make_array(T&&... values) ->
    std::array<
       typename std::decay<
           typename std::common_type<T...>::type>::type,
       sizeof...(T)> {
    return std::array<
        typename std::decay<
            typename std::common_type<T...>::type>::type,
        sizeof...(T)>{std::forward<T>(values)...};
}