Why does std::array not have an constructor that takes a value for the array to be filled with?

前端 未结 4 1709
南方客
南方客 2020-11-30 05:38

Is the absence of

std::array::array(const T& value);

an oversight? It seems mighty useful to me, and dynamic containers (

4条回答
  •  温柔的废话
    2020-11-30 05:47

    You may use std::index sequence for that:

    namespace detail
    {
    
        template 
        constexpr std::array
        make_array(const T& value, std::index_sequence)
        {
            return {{(static_cast(Is), value)...}};
        }
    }
    
    template 
    constexpr std::array make_array(const T& value)
    {
        return detail::make_array(value, std::make_index_sequence());
    }
    

    Demo

    std::make_index_sequence is C++14, but can be implemented in C++11.

    static_cast(Is) is to handle evil operator, that T might provide.

提交回复
热议问题