c/c++ 右值引用,forward关键字

c++ forward关键字

forward的由来:模板函数中的推导类型,作为函数的参数时,即使用T&& arg来声明,推导出来具体的类型后,也不能把推导出来后的具体类型,转化成右值引用。forward就是为了解决这个问题的。

forward() 函数的作用:它接受一个参数,然后返回该参数本来所对应的类型的引用。

下面的例子就不能够调用

void rvalue_call(int&& v)
void rvalue_call(const int&& v)
include <iostream>
using namespace std;

void rvalue_call(int& v){
  cout << "& call" << endl;
}
void rvalue_call(int&& v){
  cout << "&& call" << endl;
}
void rvalue_call(const int& v){
  cout << "const & call" << endl;
}
void rvalue_call(const int&& v){
  cout << "const && call" << endl;
}

template<typename T>
void func(T&& a){
  rvalue_call(a);
}

int main(void){
  int x = 1;
  func(x);//实参为左值                                           
  int& y = x;
  func(y);//实参为左值引用                                       
  func(std::move(y));//实参为右值引用                            
  func(100);//实参为右值引用          
  const int a = 11;
  func(a);//实参为左值常引用   
  func(std::move(a));//实参为右值常引用   
}

解决办法:加std::forward

#include <iostream>
using namespace std;

void rvalue_call(int& v){
  cout << "& call" << endl;
}
void rvalue_call(int&& v){
  cout << "&& call" << endl;
}
void rvalue_call(const int& v){
  cout << "const & call" << endl;
}
void rvalue_call(const int&& v){
  cout << "const && call" << endl;
}

template<typename T>
void func(T&& a){
  rvalue_call(std::forward<T> (a));
}

int main(void){
  int x = 1;
  func(x);//实参为左值                                           
  int& y = x;
  func(y);//实参为左值引用                                       
  func(std::move(y));//实参为右值引用                            
  func(100);
    
  const int a = 11;
  func(a);
  func(std::move(a));
}

猜你喜欢

转载自www.cnblogs.com/xiaoshiwang/p/9589008.html