C++17 structured binding that also includes an existing variable

后端 未结 2 1601
谎友^
谎友^ 2020-12-11 01:20

This SO answer lists some shortcomings of C++17 decomposition declarations (the feature formerly known as \"structured binding\"). For example, you can\'t give explicit type

2条回答
  •  抹茶落季
    2020-12-11 01:55

    This is a really dumb idea that I wouldn't seriously suggest unless there ends up being no sane workaround... but consider the following code.

    template
    auto plus(std::index_sequence)
    {
        return std::index_sequence{};
    }
    
    template
    auto tuple_select(RHS&& rhs, std::index_sequence)
    {
        return std::forward_as_tuple(std::get(std::forward(rhs))...);
    }
    
    template
    struct AndTie {
        std::tuple v;
        AndTie(Ts&... vs) : v(vs...) {}
    
        template
        auto operator=(RHS&& rhs) && {
            constexpr int N = std::tuple_size_v;
            constexpr int K = sizeof...(Ts);
            v = tuple_select(std::forward(rhs), plus(std::make_index_sequence{}));
            return tuple_select(std::forward(rhs), std::make_index_sequence{});
        }
    };
    

    This gives us

    auto [key] =AndTie(p)= load_string(p, end);
    auto [value] =AndTie(p)= load_value(p, end);
    

    It still has the limitation that the "tied" lvalues are constrained to appear last and the "declared" variables are constrained to appear first, but I don't think there's much way to get around that. And something like tuple_shuffle could handle that if you needed it.

提交回复
热议问题