std::tie和std::make_tuple在使用std::ref参数时有什么区别?

22

写表达式时,是否存在语义上的区别

std::tie( x, y, z )

接下来的表达式是什么?

std::make_tuple( std::ref(x), std::ref(y), std::ref(z) )

如果是这样,有什么不同之处?

顺便说一下,这个问题与使用std::tie和引用元组进行赋值有什么区别?不同,因为引用元组不是通过std::ref创建的,而是通过明确指定类型来创建的。

2个回答

19

两种表达方式几乎没有功能上的区别。tie()只是更短,而make_tuple()则更通用。


根据[tuple.creation],make_tuple的作用是:

template<class... Types>
constexpr tuple<VTypes...> make_tuple(Types&&... t);

Let Ui be decay_t<Ti> for each Ti in Types. Then each Vi in VTypes is X& if Ui equals reference_wrapper<X>, otherwise Vi is Ui.

因此,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 in t is ignore, assigning any value to the corresponding tuple element has no effect.

因此,std::tie(x, y, z) 也会产生一个 std::tuple<X&, Y&, Z&>

在一个边缘情况除外。


16

当任何一个 xyzstd::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&>
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接