首页 > 解决方案 > 从函数调用传递值时,std::tie 因“无法绑定非常量左值引用”而失败

问题描述

我希望这段代码可以工作,但它不能编译:

#include <tuple>

struct S
{
    int x = 0;
    int y() const { return 1; }
};

bool f(const S& a, const S& b)
{
    return std::tie(a.x, a.y()) < std::tie(b.x, b.y());
}

GCC 9 说:

错误:无法将“int&”类型的非常量左值引用绑定到“int”类型的右值

return std::tie(a.x, a.y()) < std::tie(b.x, b.y());
                     ~~~^~

代码有什么问题,如何修复,为什么?我正在尝试编写一个简洁的比较函数,并且通常std::tie支持它(实际上这是教科书的用例std::tie)。

演示:https ://godbolt.org/z/cWbQC0

标签: c++c++11compiler-errorslvalue

解决方案


std::tie总是期望参数的左值,因为它的预期目的是用于赋值。要处理其他值类别,可以使用std::forward_as_tuple

bool f(const S& a, const S& b)
{
    return std::forward_as_tuple(a.x, a.y()) < std::forward_as_tuple(b.x, b.y());
}

这两个元组现在包含绑定到调用结果的右值引用S::y。不用说,在使用它时最好小心对象的生命周期。


推荐阅读