c/c + + right value reference, forward keyword

c++ forward keyword

The origin of forward: when the derivation type in template function is used as the parameter of function, that is to say, T & & arg is used to declare. After the specific type is derived, the specific type after derivation cannot be converted into right value reference. Forward is to solve this problem.

The forward() function takes a parameter and returns a reference to the type that the parameter originally corresponds to.

The following example cannot be called

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);//Argument is left                                           
  int& y = x;
  func(y);//Argument is an lvalue reference                                       
  func(std::move(y));//Argument is right value reference                            
  func(100);//Argument is right value reference          
  const int a = 11;
  func(a);//Arguments are often quoted as left values   
  func(std::move(a));//Arguments are right value constant references   
}

Solution: add 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);//Argument is left                                           
  int& y = x;
  func(y);//Argument is an lvalue reference                                       
  func(std::move(y));//Argument is right value reference                            
  func(100);
    
  const int a = 11;
  func(a);
  func(std::move(a));
}

Keywords: C++

Added by bamse on Sat, 04 Jan 2020 12:08:01 +0200