The Forwarding Problem: Arguments
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2002/n1385.htm
#include<iostream>
#include<string>
using namespace std;
void incr(long &l)
{
++l;
cout << l << endl; //输出2
}
template<class A1> void fwd(A1 && a1)
{
incr(a1);
}
void f()
{
int i(5);
//error C2664: “void incr(long &)”: 无法将参数 1 从“int”转换为“long &”
// correctly fails to compile.这里的意思按照规定应该要报错.note:一个参数是引用传值方式,
//不管是左值引用还是右值引用,编译器都不会进行隐式类型转换,所以一个int&类型传入一个以long&为参数的函数,必定报错.如果在i前加上强制类型转换,则可以正常运行.
//fwd(i);
fwd((long)i); //输出6
cout << i << endl; //输出5,因为上面函数中修改是临时变量而不是i本身.
//下面的英文注释是原文中出现的,但是自己在vs中试了下,并未报错,并输出2
fwd(1L); // compiles, but shouldn't.
/*下面分析一下,fwd的调用过程:传入的参数是一个long类型的右值,对于以右值引用作为参数的fwd函数而言,通过这个1L得到一个非const的引用类型a1,在fwd体中的incr的参数
就使用的是这个a1,所以以引用类型作参数的incr函数可以正常运行.*/
}
int main()
{
f();
system("pause");
return 0;
}