问题描述
在标准(20.2.2 [utility.swap])中,为左值引用定义了std :: swap.我了解这是您想交换两件事的常见情况.但是,有时候,正确且理想的做法是交换右值(当临时对象包含引用时,例如:交换参考的临时元组).
In the standard (20.2.2 [utility.swap]), std::swap is defined for lvalue references. I understand that this is the common case for when you want to swap two things. However, there are times when it's correct and desirable to swap rvalues (when temporary objects contain references, like here: swap temporary tuples of references).
为什么右值没有重载?在右价值上进行无意义交换的风险是否超过潜在收益?
Why isn't there an overload for rvalues? Does the risk of doing a meaningless swap on rvalues outweigh the potential benefits?
是否有合法方法支持交换包含引用的右值std :: tuple对象?对于用户定义的类型,我将专门使用swap来按值接受其参数,但是对于像std :: tuple这样的库类型,似乎并没有做同样的事情.
Is there a legal way to support swapping rvalue std::tuple objects which contain references? For a user defined type, I would specialize swap to accept its arguments by value, but it doesn't seem kosher to do the same for a library type like std::tuple.
推荐答案
如何创建一个将左值转换为左值的 lvalue_cast
实用程序函数呢?
How about instead creating an lvalue_cast
utility function that casts an rvalue to an lvalue:
#include <tuple>
#include <iostream>
template <class T>
T&
lvalue_cast(T&& t)
{
return t;
}
int
main()
{
int i = 1;
int j = 2;
swap(lvalue_cast(std::tie(i)), lvalue_cast(std::tie(j)));
std::cout << i << '\n';
std::cout << j << '\n';
}
这篇关于将std :: swap专用于右值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!