写表达式时,是否存在语义上的区别
std::tie( x, y, z )
接下来的表达式是什么?
std::make_tuple( std::ref(x), std::ref(y), std::ref(z) )
如果是这样,有什么不同之处?
顺便说一下,这个问题与使用std::tie
和引用元组进行赋值有什么区别?不同,因为引用元组不是通过std::ref
创建的,而是通过明确指定类型来创建的。
写表达式时,是否存在语义上的区别
std::tie( x, y, z )
接下来的表达式是什么?
std::make_tuple( std::ref(x), std::ref(y), std::ref(z) )
如果是这样,有什么不同之处?
顺便说一下,这个问题与使用std::tie
和引用元组进行赋值有什么区别?不同,因为引用元组不是通过std::ref
创建的,而是通过明确指定类型来创建的。
两种表达方式几乎没有功能上的区别。tie()
只是更短,而make_tuple()
则更通用。
根据[tuple.creation],make_tuple
的作用是:
因此,
template<class... Types> constexpr tuple<VTypes...> make_tuple(Types&&... t);
Let
Ui
bedecay_t<Ti>
for eachTi
in Types. Then eachVi
inVTypes
isX&
ifUi
equalsreference_wrapper<X>
, otherwiseVi
isUi
.
std::make_tuple( std::ref(x), std::ref(y), std::ref(z) )
返回一个 std::tuple<X&, Y&, Z&>
。与之相反,tie
则不会返回一个元组对象。
因此,
template<class... Types> constexpr tuple<Types&...> tie(Types&... t) noexcept;
Returns:
tuple<Types&...>(t...)
. When an argument int
isignore
, assigning any value to the corresponding tuple element has no effect.
std::tie(x, y, z)
也会产生一个 std::tuple<X&, Y&, Z&>
。
†在一个边缘情况除外。
当任何一个 x
、y
和 z
是 std::reference_wrapper
的特化时,就会有所不同。
#include <tuple>
#include <functional>
void f(std::reference_wrapper<int> x, int y, int z)
{
std::tie(x,y,z); // type is std::tuple<std::reference_wrapper<int>&, int&, int&>
std::make_tuple(std::ref(x),std::ref(y),std::ref(z)); // type is std::tuple<int&, int&, int&>
}