繁体   English   中英

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

[英]What is the difference between std::tie and std::make_tuple with std::ref arguments?

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

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); 

对于类型中的每个Ti ,设Uidecay_t<Ti> 那么VTypes每个Vi都是X&如果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; 

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

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


除了一个边缘情况

xyz中的任何一个是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&>
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM