C模板类型扣除临时值

C模板类型扣除临时值,第1张

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

总结

以上是内存溢出为你收集整理的C模板类型扣除临时值全部内容,希望文章能够帮你解决C模板类型扣除临时值所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1218619.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存