How to initialize std::array elegantly if T is not default constructible?

后端 未结 3 707
名媛妹妹
名媛妹妹 2020-11-27 05:59

How do I initialize std::array if T is not default constructible?

I know it\'s possible to initialize it like that:

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 06:16

    Following will solve your issue:

    #if 1 // Not in C++11, but in C++1y (with a non linear better version)
    
    template  struct index_sequence {};
    
    template 
    struct make_index_sequence : make_index_sequence {};
    
    template 
    struct make_index_sequence<0, Is...> : index_sequence {};
    
    #endif
    
    namespace detail
    {
        template 
        constexpr std::array
        create_array(T value, index_sequence)
        {
            // cast Is to void to remove the warning: unused value
            return {{(static_cast(Is), value)...}};
        }
    }
    
    template 
    constexpr std::array create_array(const T& value)
    {
        return detail::create_array(value, make_index_sequence());
    }
    

    So test it:

    struct NoDefaultConstructible {
        constexpr NoDefaultConstructible(int i) : m_i(i) { }
        int m_i;
    };
    
    int main()
    {
        constexpr auto ar1 = create_array<10>(NoDefaultConstructible(42));
        constexpr std::array ar2 = create_array<10>(NoDefaultConstructible(42));
    
        return 0;
    }
    

提交回复
热议问题