C + + rvalue reference, forward keyword

Source: Internet
Author: User

The origin of C + + forward keyword forward: The derivation type in the template function, as the parameter of the function, that is, the use of t&& Arg to declare, after the derivation of the specific type, can not be deduced after the specific type, converted to Rvalue reference. Forward is to solve this problem.
forward() 函数的作用:它接受一个参数,然后返回该参数本来所对应的类型的引用。

The following example is not able to invoke the

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));//实参为右值常引用   }
Workaround: 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);//实参为左值                                             int& y = x;  func(y);//实参为左值引用                                         func(std::move(y));//实参为右值引用                              func(100);      const int a = 11;  func(a);  func(std::move(a));}

C + + rvalue reference, forward keyword

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.