C++如何对右值引用进行模板推导?

Rya*_*yan 4 c++ templates rvalue-reference

template<typename T>
void foo(T&& arg);
Run Code Online (Sandbox Code Playgroud)

我知道 arg 是否是左值,例如int x = 0; foo(x);thenT = int&并且函数将为foo(int& &&),即foo(int&).

如果 arg 是一个右值,例如foo(0);然后T = int,函数将是foo(int&&).

如果我有

template<typename T>
void foo(T& arg);

template<typename U>
void bar(U&& u)
{
    foo(u);
}
Run Code Online (Sandbox Code Playgroud)

是什么Tfoo打电话时bar(0)

Okt*_*ist 5

template<typename U>
void bar(U&& u)
{
    foo(u);
}
Run Code Online (Sandbox Code Playgroud)

不管你传入什么baru都是一个左值,因为它有一个名字。

u可能是左值引用或右值引用,但是当您将它传递给 时foo,它的“引用性”会像往常一样被忽略。

暂时忘记左值、右值和模板。引用应该是另一个变量的别名,并且在大多数情况下,按名称引用引用的行为应该就像引用原始变量一样:

int i = 42;
int& r = i;

f(int);
f(int&);
f(i); // error: call to ambiguous overload
f(r); // error: call to ambiguous overload

g(int);
g(r); // OK, pass by copy, reference-ness of r is irrelevant

h(int&);
h(i); // OK, pass by reference, non-reference-ness of i is irrelevant
Run Code Online (Sandbox Code Playgroud)

在上面的函数调用语句中,id 表达式 ir是类型的左值int变量 ir分别是非引用和引用的事实与相应id-expressions的类型或值类别无关。这是引用一直有效的方式,右值引用不会改变这一点。

template<typename T>
void foo(T& arg);
Run Code Online (Sandbox Code Playgroud)

没有什么,你可以传递给foo这将使T是引用类型。arg将始终是左值引用。

如果要传播参数的值类别,则需要std::forward

template<typename U>
void baz(U&& u)
{
    foo(std::forward<U>(u));
}

baz(42); // error: attempted to call foo() with an rvalue
Run Code Online (Sandbox Code Playgroud)