C++17: Keep only some members when tuple unpacking

前端 未结 4 1257
囚心锁ツ
囚心锁ツ 2020-12-25 10:23

Let\'s imagine you need to call the following method:

std::tuple foo();

In C++17, you can call the function and unpack

4条回答
  •  忘掉有多难
    2020-12-25 11:26

    You could write a helper function that only gives you back certain indices of a std::tuple:

    template 
    auto take_only(Tuple&& tuple) {
        using T = std::remove_reference_t;
    
        return std::tuple...>(
            std::get(std::forward(tuple))...);
    }
    
    auto [b, c] = take_only<1, 2>(foo());
    

    Or drops the head or something:

    template 
    auto drop_head_impl(Tuple&& tuple, std::index_sequence<0, Is...> ) {
        return take_only(std::forward(tuple));
    }
    
    template 
    auto drop_head(Tuple&& tuple) {
        return drop_head_impl(std::forward(tuple),
            std::make_index_sequence>>());
    }
    
    auto [b, c] = drop_head(foo());
    

    But the above implementations almost certainly have some lifetime complexity issues that directly using structured bindings won't - since there isn't any lifetime extension here.

    So just, do what Vittorio says:

    auto [a, b, c] = foo();
    (void)a;
    

提交回复
热议问题