[英]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
,设Ui
为decay_t<Ti>
。 那么VTypes
每个Vi
都是X&
如果Ui
等于reference_wrapper<X>
,否则Vi
是Ui
。
因此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&>
。
†除了一个边缘情况 。
当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&>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.