std :: tie和std :: make_tuple与std :: ref参数有什么区别?

Ral*_*zky 20 c++ tuples reference c++11

写表达式之间是否存在语义差异

std::tie( x, y, z )
Run Code Online (Sandbox Code Playgroud)

和以下表达式?

std::make_tuple( std::ref(x), std::ref(y), std::ref(z) )
Run Code Online (Sandbox Code Playgroud)

如果是这样,有什么区别?

顺便说一句,这个问题并不是一样的问题.分配给std::tie引用和元组之间的区别什么因为引用元组不是通过std::ref,而是通过显式指定类型创建的.

Bar*_*rry 18

这里几乎两个表达式之间没有功能上的差异.tie()只是更短,而make_tuple()更通用.


根据[tuple.creation],make_tuple确实:

template<class... Types>
constexpr tuple<VTypes...> make_tuple(Types&&... t);
Run Code Online (Sandbox Code Playgroud)

我们Ui可以decay_t<Ti>为每个Ti类型研究.然后,每个ViVTypesX&如果Ui等号reference_wrapper<X>,否则ViUi.

因此std::make_tuple( std::ref(x), std::ref(y), std::ref(z) )产量 a std::tuple<X&, Y&, Z&>.

另一方面,tie确实:

template<class... Types>
constexpr tuple<Types&...> tie(Types&... t) noexcept;
Run Code Online (Sandbox Code Playgroud)

返回: tuple<Types&...>(t...).当参数为tis时ignore,将任何值赋给相应的元组元素都没有效果.

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


除了一个边缘情况.


cpp*_*ner 16

任何一个都是有区别的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&>
}
Run Code Online (Sandbox Code Playgroud)