Cha*_*429 3 c++ templates perfect-forwarding c++11
该计划如下:
#include <iostream>
using namespace std;
template <typename F, typename T1, typename T2>
void flip2(F f, T1 &&t1, T2 &&t2)
{
f(t2, t1);
}
void g(int &&i, int &j)
{
cout << i << " " << j << endl;
}
int main(void)
{
int i = 1;
flip2(g, i, 42);
}
Run Code Online (Sandbox Code Playgroud)
编译器抱怨:
error: rvalue reference to type 'int' cannot bind to lvalue of type 'int'
Run Code Online (Sandbox Code Playgroud)
但据我所知,正如T2实例化那样int,那么类型t2是int&&,所以应该允许它传递给函数g的第一个参数(int &&).
我的理解有什么问题?
f(t2, t1);
Run Code Online (Sandbox Code Playgroud)
t2有一个名字,所以它是一个左值.它的类型是rvalue,但在表达式中它的类型是左值.为了将它作为右值引用传递,你需要使用std::forward(move或者在这里使用转换是不合适的,因为T1和T2实际上是通用引用,而不是右值引用,请参见编辑).
#include <iostream>
using namespace std;
template <typename F, typename T1, typename T2>
void flip2(F f, T1 &&t1, T2 &&t2)
{
f(std::forward<T2>(t2), std::forward<T1>(t1));
}
void g(int &&i, int &j)
{
cout << i << " " << j << endl;
}
int main(void)
{
int i = 1;
flip2(g, i, 42);
}
Run Code Online (Sandbox Code Playgroud)
---为什么---
考虑:
template<typename T>
void printAndLog(T&& text) {
print(text);
log(text);
}
int main() {
printAndLog(std::string("hello, world!\n"));
}
Run Code Online (Sandbox Code Playgroud)
当你使用变量的名字时,表达式类型是lvalue(glvalue?); rvalueness被丢弃.否则在上面的例子中,我们已经输text了print().相反,当我们希望我们的rvalue表现得像一个时,我们必须明确:
template<typename T>
void printAndLog(T&& text) {
print(text);
log(std::forward<T>(text)); // if text is an rvalue, give it up.
}
Run Code Online (Sandbox Code Playgroud)
---编辑---
我使用std::forward因为T1&&并且T2&&是通用引用,而不是右值引用.https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers