了解使用rvalue / lvalue的模板参数扣除 [英] Understanding template argument deduction with rvalue/lvalue
问题描述
使用以下代码播放:
#include < iostream>
template< class T>
void func(T&&){
std :: cout<<in rvalue\\\
;
}
template< class T>
void func(const T&){
std :: cout<<in lvalue\\\
;
}
int main()
{
double n = 3;
func< double>(n);
func(n);
}
打印:
in lvalue
in rvalue
不知道第二次电话会发生什么。编译器
如何解析模板参数?
当你说 / code>,没有参数扣除,因为你指定参数,所以选择在 第一个重载更严格,参数值的少一个转换(即从 魔法成分是参考折叠,这意味着 This is a followup from template function does not recognize lvalue Lets play with the following code: It prints: I don't understand what's happening in the second call. How the compiler
resolve the template parameter ? Why isn't there any ambiguity ? When you say Only The first overload is strictly better, because it requires one less conversion of the argument value (namely from The magic ingredient is the "reference collapsing", which means that 这篇关于了解使用rvalue / lvalue的模板参数扣除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! func< double>(n)
func(double&&)
和 func(const double&)
。前者是不可行的,因为右值引用不能绑定到左值(即 n
)。
func(n)
执行参数扣除。这是一个复杂的主题,但简而言之,你有这两个可能的候选人:
T = double&:func(T&&) - > func(double&)(first overload)
T = double:func(const T&) - > func(const double&)(第二重载)
double
到 const double
)。
当
T
本身是引用类型(specificaly, double&&&& ;&
变为 double&
,并允许第一次扣除存在)。#include <iostream>
template <class T>
void func(T&&) {
std::cout<<"in rvalue\n";
}
template <class T>
void func(const T&) {
std::cout<<"in lvalue\n";
}
int main()
{
double n=3;
func<double>(n);
func(n);
}
in lvalue
in rvalue
func<double>(n)
, there's no argument deduction, since you specify the argument, and so the choice is between func(double &&)
and func(const double &)
. The former isn't viable, because an rvalue reference cannot bind to an lvalue (namely n
).func(n)
performs argument deduction. This is a complex topic, but in a nutshell, you have these two possible candidates:T = double &: func(T &&) --> func(double &) (first overload)
T = double: func(const T &) --> func(const double &) (second overload)
double
to const double
).T &&
can be an lvalue reference when T
is itself a reference type (specificaly, double & &&
becomes double &
, and that allows the first deduction to exist).