右值参考参数和模板功能 [英] Rvalue reference parameters and template functions

查看:71
本文介绍了右值参考参数和模板功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我定义一个接受右值引用参数的函数:

If I define a function which accepts an rvalue reference parameter:

template <typename T>
void fooT(T &&x) {}

我可以这样称呼,使用GCC 4.5,使用 a ar arr

I can call it, using GCC 4.5, with either a, ar, or arr:

int a, &ar = a, &&arr = 7;
fooT(a); fooT(ar); fooT(arr);

但是,调用类似的 non-template 函数

void fooInt(int &&x) {}

带有这三个参数中的任何一个都会失败。我正准备加强对前进的了解,但这使我偏离了方向。也许是GCC 4.5;我很惊讶地发现, Rvalue引用简介的第一个示例也给出了一个编译错误:

with any of those three arguments will fail. I was preparing to strengthen my knowledge of forward, but this has knocked me off course. Perhaps it's GCC 4.5; I was surprised to find that the first example from A Brief Introduction to Rvalue References also gives a compile error:

A a;
A&& a_ref2 = a;  // an rvalue reference


推荐答案

模板中的演绎行为参数是唯一的,并且是模板版本起作用的原因。在另一个上下文的背景下,我在这里详细说明了这种扣除的工作原理问题。

The behavior of deduction in template parameters is unique, and is the reason your template version works. I've explained exactly how this deduction works here, in the context of another question.

总结:当参数为左值时, T 推导为 T& ; T& & 折叠为 T& 。并且使用参数 T& ,向其提供左值 T 是完全有效的。否则, T 仍为 T ,并且参数为 T& ,它接受rvalues参数。

Summarized: when the argument is an lvalue, T is deduced to T&, and T& && collapses to T&. And with the parameter at T&, it is perfectly valid to supply an lvalue T to it. Otherwise, T remains T, and the parameter is T&&, which accepts rvalues arguments.

相反, int&& c始终为 int& (没有模板推导规则可将其强制转换为其他值),并且只能绑定到右值。

Contrarily, int&& is always int&& (no template deduction rules to coerce it to something else), and can only bind to rvalues.

这篇关于右值参考参数和模板功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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