c++ - 从函数调用传递值时,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
)。
解决方案
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
。不用说,在使用它时最好小心对象的生命周期。
推荐阅读
- entity-framework - asp.net core中的多对多关系和多选
- html - 如何限制屏幕阅读器不阅读特定文本?
- git - .gitignore 检查零件名称到文件夹以忽略所有文件和子文件夹
- reactjs - reactjs:TypeError:无法读取未定义的属性“来自”
- c++ - 如何在 wxWIdgets 中显示清晰的图标
- python-2.7 - HP ALM - 无法通过 python 将附件发布到缺陷
- java - 函数和谓词参数不明确?
- java - 使用 RestFB 列出组
- css - 如何切断两个并排div中第二个的下部?
- c# - 在 C# 中获取用户输入并将其添加到数组中