C++-Universal Reference Template and Perfect Forwarding Test

Perfect forwarding, which means that a function template can "perfectly" forward its own parameters to other functions that are called internally. The so-called perfection means that not only the value of the parameter can be accurately forwarded, but also the left and right value attributes of the forwarded parameter can be guaranteed unchanged.

Universal reference, perfect forwarding, and reference folding in modern C++ (thousand-word long text)

Detailed explanation of C++11 perfect forwarding and implementation methods

std::forward perfect forwarding

Perfect Forwarding: The Solution

Universal reference and perfect forwarding test code

#include<iostream>
using namespace std;
//重载被调用函数,查看完美转发的效果
void bar(string & t) {
    
    
	cout << "bar收到参数:string &" << endl;
}
void bar(const string & t) {
    
    
	cout << "bar收到参数:const string &" << endl;
}
void bar(string && t) {
    
    
	cout << "bar收到参数:string &&" << endl;
}
void bar(const string && t) {
    
    
	cout << "bar收到参数:const string &&" << endl;
}
//万能引用与完美转发函数模板
template <typename T>
void foo(T&& value) 
{
    
     
	bar(forward<T>(value));
}
int main()
{
    
    
	//传给foo一个string &
	string str1;
	string & str2 = str1;
	foo(str2);
	//传给foo一个string
	foo(str1);
	//传给foo一个const string
	const string str3;
	foo(str3);
	//传给foo一个const string &
	const string & str4 = str1;
	foo(str4);
	//传给foo一个string &&
	foo(move(str1));
	//传给foo一个const string &&
	foo(move(str3));
	return 0;
}

Test Results

insert image description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324109255&siteId=291194637