Convert std::tuple to std::array C++11

后端 未结 7 1052
情话喂你
情话喂你 2020-11-27 17:00

If I have std::tuple (where the type is homogeneous), is there a stock function or constructor to convert to std::array

7条回答
  •  爱一瞬间的悲伤
    2020-11-27 17:37

    In C++14 you can do this to generate an array:

    auto arr = apply([](auto... n){return std::array{n...};}, tup);
    

    Full code:

    #include // apply
    #include
    
    //using std::experimental::apply; c++14 + experimental
    using std::apply; // c++17
    
    template
    auto to_array(Tuple&& t){
        return apply([](auto... n){return std::array{n...};}, t); // c++14 + exp
    }
    
    int main(){
        std::tuple t{2, 3, 4};
    
        auto a = apply([](auto... n){return std::array{n...};}, t); // c++14 + exp
        assert( a[1] == 3 );
    
        auto a2 = apply([](auto... n){return std::array{n...};}, t); // c++14 + exp
        assert( a2[1] == 3 );
    
        auto a3 = apply([](auto... n){return std::array{n...};}, t); // c++17
        assert( a3[1] == 3 );
    
        auto a4 = to_array(t);
        assert( a4[1] == 3 );
    
    }
    

    Note that the subtle problem is what to do when all types in the source tuple are not the same, should it fail to compile? use implicit conversion rules? use explicit conversion rules?

提交回复
热议问题