我正在阅读参考折叠规则,我有一个问题:如果我将rvalue A传递给
template<typename T>
void foo(T&&);T被推断为A?
如果我把std::string()传递给函数T是std::string,为什么不是std::string&&呢?这对我来说更有意义,将T推断为类型本身的理由是什么?
发布于 2016-03-30 11:53:27
这与我们从模板类型推断中所期望的只是一致的:
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来自原稿,重点是我的:
当使用与rvalue引用匹配的lvalue参数推断函数模板类型时,该类型被推断为lvalue引用类型。当给出一个rvalue参数时,类型的演绎将和其他类型一样进行。
这是一个特殊的情况,这就是为什么它会在类型演绎规则中得到一个额外的句子。rvalue案例是典型的-它与简单的心理模型贴图在推导的类型,看看你结束了什么功能。叫T&&有std::string?获取T = std::string,以便参数读取std::string&&。检查一下。
发布于 2016-03-30 11:47:19
因为函数参数类型有&& on,所以您将推断表达式的'T‘部分。
因此,将std::string&&‘传递’给T&&将把T推断为std::string。
将std::string替换为T在表达式T&&中生成std::string&&。
这与在表达式T const&中推导T const&类似;当通过const引用“传递”std::string时,T部分被推导为std::string。
https://stackoverflow.com/questions/36307479
复制相似问题