/**
* 功能:模板左值右值的转换
* 时间:2014年7月27日08:18:06
* 作者:cutter_point
*/
#include
#include
#include
using namespace std;
template
auto fcn(It beg, It end) -> typename remove_reference::type
{
return *beg; //这里返回的是beg的一个拷贝,因为用了remove_reference去除了引用
}
/**************************************
Function Pointers and Argument Deduction
**************************************/
template
int compare(const T &, const T &){cout<<"templateint compare(const T &, const T &)"<);
}
/**************************************
Template Argument Deduction and References
**************************************/
/**
Type Deduction from Lvalue Reference Function Parameters
*/
/*
见word文档
*/
/**
Type Deduction from Rvalue Reference Function Parameters
*/
/*
见word文档
*/
/**
Writing Template Functions with Rvalue Reference Parameters
写一个模板函数带有右值引用参数
*/
template
T fcn2(T &t)
{
cout<<"t的值是:"<
void f3(T &&val)
{
T t=val;
t=fcn2(t);
if(val == t)
{
cout<<"void f3(T &&val),val == t"<
typename remove_reference::type &&move(T &&t)//右值
{
//static_cast就相当于显示地类型转换,百度百科里面是这样
/*
int i;
float f=166.71;
i=static_cast(f);
结果i是166
*/
return static_cast::type &&>(t); //都是右值!!
}
void fun2()
{
string s1("hi!"), s2;
s2=std::move(string("bye!")); //ok:从一个右值移动
cout<<"s2=std::move(string(bye!));s2:"<
void flip1(F f, T1 t1, T2 t2)
{
f(t1, t2);
}
void f(int v1, int &v2) //v2是一个引用
{
cout<
void flip2(F f, T1 &&t1, T2 &&t2) //两个都是右值引用!!
{
f(t1, t2); //吧t1+1输出。两个右值引用,那么t1和t2的值是变了的
}
void fun4()
{
flip2(f, 8, 8);
cout<<"flip2(f, i, j);j:"<
void flip(F f, T1 &&t1, T2 &&t2)
{
f(std::forward(t1), std::forward(t2));
}
void fun5()
{
int j=8;
flip(f, j, j); //这里和上面有点不同了,注意这里第二个j要填左值参数,因为在f里面将第二个j的值改变了
//所以这里虽然传的是形参,但是forward把它还原成右值引用了,还是会改变大小
cout<<"flip(f, i, j);j:"<>------------------------------fun1-----------------------------------<<"<>------------------------------fun2-----------------------------------<<"<>------------------------------fun3-----------------------------------<<"<>------------------------------fun4-----------------------------------<<"<>------------------------------fun5-----------------------------------<<"<