How to initialize all members of an array to the same value?

后端 未结 23 1807
清歌不尽
清歌不尽 2020-11-21 04:34

I have a large array in C (not C++ if that makes a difference). I want to initialize all members of the same value.

I could swear I

23条回答
  •  执笔经年
    2020-11-21 05:20

    I know the original question explicitly mentions C and not C++, but if you (like me) came here looking for a solution for C++ arrays, here's a neat trick:

    If your compiler supports fold expressions, you can use template magic and std::index_sequence to generate an initializer list with the value that you want. And you can even constexpr it and feel like a boss:

    #include 
    
    /// [3]
    /// This functions's only purpose is to ignore the index given as the second
    /// template argument and to always produce the value passed in.
    template
    constexpr T identity_func(const T& value) {
        return value;
    }
    
    /// [2]
    /// At this point, we have a list of indices that we can unfold
    /// into an initializer list using the `identity_func` above.
    template
    constexpr std::array
    make_array_of_impl(const T& value, std::index_sequence) {
        return {identity_func(value)...};
    }
    
    /// [1]
    /// This is the user-facing function.
    /// The template arguments are swapped compared to the order used
    /// for std::array, this way we can let the compiler infer the type
    /// from the given value but still define it explicitly if we want to.
    template
    constexpr std::array 
    make_array_of(const T& value) {
        using Indices = std::make_index_sequence;
        return make_array_of_impl(value, Indices{});
    }
    
    // std::array{42, 42, 42, 42}
    constexpr auto test_array = make_array_of<4/*, int*/>(42);
    static_assert(test_array[0] == 42);
    static_assert(test_array[1] == 42);
    static_assert(test_array[2] == 42);
    static_assert(test_array[3] == 42);
    // static_assert(test_array[4] == 42); out of bounds
    

    You can take a look at the code at work (at Wandbox)

提交回复
热议问题