了解使用rvalue / lvalue的模板参数扣除 [英] Understanding template argument deduction with rvalue/lvalue

查看:158
本文介绍了了解使用rvalue / lvalue的模板参数扣除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是模板功能无法识别lvalue的后续跟踪

a>



使用以下代码播放:

  #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

不知道第二次电话会发生什么。编译器
如何解析模板参数?

当你说 func< double>(n)

/ code>,没有参数扣除,因为你指定参数,所以选择在 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& ,并允许第一次扣除存在)。


This is a followup from template function does not recognize lvalue

Lets play with the following code:

#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);
}

It prints:

in lvalue
in rvalue

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 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).

Only 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)

The first overload is strictly better, because it requires one less conversion of the argument value (namely from double to const double).

The magic ingredient is the "reference collapsing", which means that 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).

这篇关于了解使用rvalue / lvalue的模板参数扣除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆