维护对元素引用类型

Maintain pair element reference type

有什么方法可以转发一对(或元组)的元素,同时保持其引用类型(例如,继续为右值)?

下面的例子展示了我的尝试:转发和移动一对元素(第一个和第二个),移动对并使用它的元素,以及移动对和元素。我希望所有人都能正常工作,但 none 确实如此。

template<class T, class U>
auto pair_forward(std::pair<T, U>&& p)
{
    return std::make_pair(std::forward<T>(p.first), std::forward<U>(p.second));
}

template<class T, class U>
auto pair_move_elem(std::pair<T, U>&& p)
{
    return std::make_pair(std::move(p.first), std::move(p.second));
}

template<class T, class U>
auto move_pair(std::pair<T, U>&& p)
{
    return std::make_pair(std::move(p).first, std::move(p).second);
}

int main()
{
    int x;
    std::pair<int, int&&> p(x, std::move(x));
    static_assert(std::is_rvalue_reference<decltype(p.second)>::value); // works

    auto t1 = pair_forward(std::move(p));
    static_assert(std::is_rvalue_reference<decltype(t1.second)>::value); // fails

    auto t2 = pair_move_elem(std::move(p));
    static_assert(std::is_rvalue_reference<decltype(t2.second)>::value); // fails

    auto t3 = move_pair(std::move(p));
    static_assert(std::is_rvalue_reference<decltype(t3.second)>::value); // fails
}

make_pair的推导规则让我感到困惑,所以我建议直接用你想要的类型调用构造函数。

#include <utility>

template<class T, class U>
auto pair_forward(std::pair<T, U>&& p)
{
    return std::pair<T, U>(std::forward<T>(p.first), std::forward<U>(p.second));
}

template<class T, class U>
auto pair_move_elem(std::pair<T, U>&& p)
{
    return std::pair<T&&, U&&>(std::move(p.first), std::move(p.second));
}

template<class T, class U>
auto move_pair(std::pair<T, U>&& p)
{
    return std::pair<T, U>(std::move(p));
    // or just: return std::pair(std::move(p));
}

int main()
{
    int x;
    std::pair<int, int&&> p(x, std::move(x));
    static_assert(std::is_rvalue_reference<decltype(p.second)>::value); // works

    auto t1 = pair_forward(std::move(p));
    static_assert(std::is_rvalue_reference<decltype(t1.second)>::value); // works

    auto t2 = pair_move_elem(std::move(p));
    static_assert(std::is_rvalue_reference<decltype(t2.second)>::value); // works

    auto t3 = move_pair(std::move(p));
    static_assert(std::is_rvalue_reference<decltype(t3.second)>::value); // works
}

直播:https://godbolt.org/z/EfGe_x