微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C模板类型扣除临时值

#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&并绑定临时就好了.但这只是一种在实践中不太可能有用的好奇心.使用转发参考.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐