右转转发参考 [英] Rvalue to forwarding references
问题描述
我正在阅读引用折叠规则,我有一个问题:为什么我将右值A 传递给
I'm reading the reference collapsing rules and I have a question: why if I pass a rvalue A to
template<typename T>
void foo(T&&);
T推论为A?
例如如果我将 std :: string()
传递给函数 T
推导为 std :: string
,为什么不是 std::string&&
?对我来说,这更有意义,将 T
推导为类型本身的原理是什么?
e.g. if I pass std::string()
to the function T
is deduced to be std::string
, why not std::string&&
? It would have made more sense to me, what's the rationale behind deducing T
to the type itself?
推荐答案
这仅与我们从模板类型推导中获得的期望基本一致:
This merely lines up with what we expect in general from template type deduction:
template <class T> void vfoo(T );
template <class T> void lfoo(T& );
template <class T> void cfoo(T const& );
template <class T> void ffoo(T&& );
std::string x;
vfoo(x); // deduce T = std::string
lfoo(x); // deduce T = std::string
cfoo(x); // deduce T = std::string
ffoo(x); // deduce T = std::string& !
ffoo(std::move(x)); // deduce T = std::string
来自原始论文,重点是:
当使用与右值引用匹配的左值参数推导函数模板类型时,该类型被推导为左值引用类型.当给定推导一个右值参数时,类型推导与其他类型一样进行.
这是左值扣除案例,这是例外,这就是为什么它在类型推断规则中得到一个额外的句子.右值情况很典型-它与粘贴推论类型的简单思维模型一致,以查看最终要使用的功能.用 std :: string
称为 T&
?获取 T = std :: string
,以便该参数读取 std :: string&&
.查看.
It's the lvalue deduction case that's the exceptional one, which is why it gets an extra sentence in the type deduction rules. The rvalue case is typical - it lines up with the simple mental model of pasting in the deduced types to see what function you end up with. Called T&&
with a std::string
? Get T = std::string
so that the argument reads std::string&&
. Check.
这篇关于右转转发参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!