gpt4 book ai didi

c++ - 转发引用的右值

转载 作者:可可西里 更新时间:2023-11-01 15:08:52 25 4
gpt4 key购买 nike

我正在阅读 reference collapsing rules我有一个问题:为什么我将 rvalue A 传递给

template<typename T>
void foo(T&&);

T被推导为A?

例如如果我将 std::string() 传递给函数 T 被推断为 std::string,为什么不是 std: :字符串&&?这对我来说更有意义,将 T 推导为类型本身的基本原理是什么?

最佳答案

这仅仅符合我们对模板类型推导的一般预期:

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

来自 the original paper ,强调我的:

When deducing a function template type using an lvalue argument matching to an rvalue reference, the type is deduced as an lvalue reference type. When deduction is given an rvalue argument, type deduction proceeds just as with other types.

左值推导情况是异常(exception)情况,这就是为什么它在类型推导规则中有一个额外的句子。右值情况是典型的——它与在推导类型中粘贴的简单心智模型一致,以查看最终得到的函数。使用 std::string 调用了 T&&?获取 T = std::string 以便参数读取 std::string&&。查看。

关于c++ - 转发引用的右值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36307479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com