加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C模板类型扣除临时值

发布时间:2020-12-16 10:14:39 所属栏目:百科 来源:网络整理
导读:#include iostream#include vectorusing namespace std;template typename Tvoid wrapper(T u){ g(u);}class A {};void g(const A a) {}int main(){ const A ca; wrapper(ca); wrapper(A()); // Error} 嗨,我有一个问题,为什么最后一个语句给出编译器错误. :
#include <iostream>
#include <vector>
using namespace std;

template <typename T>
void wrapper(T& u)
{
    g(u);
}

class A {};

void g(const A& a) {}
int main()
{
    const A ca;
    wrapper(ca);
    wrapper(A()); // Error
}

嗨,我有一个问题,为什么最后一个语句给出编译器错误.

:18:10: error: cannot bind non-const lvalue reference of type
‘A&’ to an rvalue of type ‘A’ wrapper(A());

我认为模板类型T将被推导为const A&因为ca也被推断为const A&amp ;.在这种情况下,为什么类型扣除失败?

解决方法

I thought that the template type T would be deduced as const A& as the ca is also deduced as const A&. Why the type deduction fails in this case?

因为这不是演绎规则的工作方式.他们努力尽可能地推断出与函数参数类型的匹配.临时不一定是const,它只能绑定到const引用.

但是你的函数模板不接受const引用,而是接受非const左值引用.因此,除非函数参数是const本身(它不是),否则没有const会出现.

正确的解决方案是使用转发引用(对推导的模板参数的右值引用):

template <typename T>
void wrapper(T&& u)
{
    g(std::forward<T>(u));
}

现在你可以绑定到任何对象.推导出的类型将告诉您函数参数的值类别,允许您将该类别转发给函数调用g(…),并确保选择正确的重载.

顺便说一句,如果你好奇,如果你将const直接添加到临时类型,你的原始代码将建立得很好.

using CA = A const;
wrapper(CA()); // Not an error anymore

现在你最终成为一个A const&并绑定临时就好了.但这只是一种在实践中不太可能有用的好奇心.使用转发参考.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读