C++11特性

1.列表初始化

1.1C++98传统的{}

C++98中⼀般数组和结构体可以⽤{}进⾏初始化

cpp 复制代码
struct Point
{
int _x;
int _y;
};
int main()
{
int array1[] = { 1, 2, 3, 4, 5 };
int array2[5] = { 0 };
Point p = { 1, 2 };
return 0;
}

1.2C++11中的{}

内置类型⽀持,⾃定义类型也⽀持,⾃定义类型本质是类型转换,中间会产⽣临时对象,最后优化

了以后变成直接构造。

{}初始化的过程中,可以省略掉=

C++11列表初始化的本意是想实现⼀个⼤统⼀的初始化⽅式,其次他在有些场景下带来的不少便利,如容器push/inset多参数构造的对象时,{}初始化会很⽅便

cpp 复制代码
#include<iostream>
#include<vector>
using namespace std;
struct Point
{
	int _x;
	int _y;
};
class Date
{
public:
	Date(int year = 1, int month = 1, int day = 1)
		:_year(year)
		, _month(month)
		, _day(day)
	{
		cout << "Date(int year, int month, int day)" << endl;
	}
	Date(const Date& d)
		:_year(d._year)
		, _month(d._month)
		, _day(d._day)
	{
		cout << "Date(const Date& d)" << endl;
	}
private:
	int _year;
	int _month;
	int _day;
};
int main()
{
	// C++98⽀持的
	int a1[] = { 1, 2, 3, 4, 5 };
	int a2[5] = { 0 };
	Point p = { 1, 2 };
	// C++11⽀持的
	// 内置类型⽀持
	int x1 = { 2 };
	// ⾃定义类型⽀持
	// 这⾥本质是⽤{ 2025, 1, 1}构造⼀个Date临时对象
	// 临时对象再去拷⻉构造d1,编译器优化后合⼆为⼀变成{ 2025, 1, 1}直接构造初始化
	d1
		// 运⾏⼀下,我们可以验证上⾯的理论,发现是没调⽤拷⻉构造的
		Date d1 = { 2025, 1, 1 };
	// 这⾥d2引⽤的是{ 2024, 7, 25 }构造的临时对象
	const Date& d2 = { 2024, 7, 25 };
	// 需要注意的是C++98⽀持单参数时类型转换,也可以不⽤{}
	Date d3 = { 2025 };
	Date d4 = 2025;
	// 可以省略掉=
	Point p1{ 1, 2 };
	int x2{ 2 };
	Date d6{ 2024, 7, 25 };
	const Date& d7{ 2024, 7, 25 };
	// 不⽀持,只有{}初始化,才能省略=
	// Date d8 2025;
	vector<Date> v;
	v.push_back(d1);
	v.push_back(Date(2025, 1, 1));
	// ⽐起有名对象和匿名对象传参,这⾥{}更有性价⽐
	v.push_back({ 2025, 1, 1 });
	return 0;
}

1.3std::initializer_list

C++11库中提出了⼀个std::initializer_list的类, auto il = { 10, 20, 30 }; // the

type of il is an initializer_list

这个类的本质是底层开⼀个数组,将数据拷⻉

过来,std::initializer_list内部有两个指针分别指向数组的开始和结束。

这是他的⽂档:initializer_list,std::initializer_list⽀持迭代器遍历。

容器⽀持⼀个std::initializer_list的构造函数,也就⽀持任意多个值构成的 {x1,x2,x3...} 进⾏

初始化。STL中的容器⽀持任意多个值构成的 {x1,x2,x3...} 进⾏初始化,就是通过std::initializer_list的构造函数⽀持的。

//STL中的容器都增加了⼀个initializer_list的构造

vector(initializer_list<value_type> il, const allocator_type& alloc = allocator_type());

list(initializer_list<value_type> il, const allocator_type& alloc =allocator_type());

map(initializer_list<value_type> il, const key_compare& comp =key_compare(), const allocator_type& alloc = allocator_type());

// 另外,容器的赋值也⽀持 initializer_list 的版本
vector& operator = (initializer_list<value_type> il);
map& operator = (initializer_list<value_type> il);

cpp 复制代码
int main()
{
	std::initializer_list<int> mylist;
	mylist = { 10, 20, 30 };
	cout << sizeof(mylist) << endl;
	// 这⾥begin和end返回的值initializer_list对象中存的两个指针
	// 这两个指针的值跟i的地址跟接近,说明数组存在栈上
	int i = 0;
	cout << mylist.begin() << endl;
	cout << mylist.end() << endl;
	cout << &i << endl;
	// {}列表中可以有任意多个值
	// 这两个写法语义上还是有差别的,第⼀个v1是直接构造,
	// 第⼆个v2是构造临时对象+临时对象拷⻉v2+优化为直接构造
	vector<int> v1({ 1,2,3,4,5 });
	vector<int> v2 = { 1,2,3,4,5 };
	const vector<int>& v3 = { 1,2,3,4,5 };
	// 这⾥是pair对象的{}初始化和map的initializer_list构造结合到⼀起⽤了
	map<string, string> dict = { {"sort", "排序"}, {"string", "字符串"} };
	// initializer_list版本的赋值⽀持
	v1 = { 10,20,30,40,50 };
	return 0;
}

2.引用和移动语义

C++98的C++语法中就有引⽤的语法,⽽C++11中新增了的 右值引⽤ 语法特性,C++11出来了,之前的引⽤就叫做 左值引⽤ 。 论左值引用还是右值引用,都是给对象取别名

2.1左值和右值

左值是⼀个表⽰数据的表达式(如变量名或解引⽤的指针),⼀般是有持久状态,存储在内存中,可以获取它的地址左值 可以出现 赋值符号的 左边 , 也可以出现在 赋值符号 右边
右值也是⼀个表⽰数据的表达式,要么是字⾯值常量、要么是表达式求值过程中创建的临时对象,右值 只能出现在 赋值符号的 右边 ,且不能取地址

int a = 10; //这里的a是一个左值,10是一个右值

int b = a; //这里的a和b都是左值,都可以取他的地址

cpp 复制代码
int main()
{
	// 左值:可以取地址
	// 以下的p、b、c、*p、s、s[0]就是常⻅的左值
	int* p = new int(0);
	int b = 1;
	const int c = b;
	*p = 10;
	string s("111111");
	s[0] = 'x';
	cout << &c << endl;
	cout << (void*)&s[0] << endl;
	// 右值:不能取地址
	double x = 1.1, y = 2.2;
	// 以下⼏个10、x + y、fmin(x, y)、string("11111")都是常⻅的右值
	10;
	x + y;
	fmin(x, y);
	string("11111");
	//cout << &10 << endl;
	//cout << &(x+y) << endl;
	//cout << &(fmin(x, y)) << endl;
	//cout << &string("11111") << endl;
	return 0;
}

2.2 左值引用和右值引用

左值引用和右值引用的语法:

//左值引用

Type& r1 = x;

//右值引用

Type&& r2 = y;
左值引⽤不能 直接引⽤右值,但是const左值引⽤可以引⽤右值
右值引⽤不能直接引⽤左值,但是右值引⽤可以引⽤move(左值)

move是库⾥⾯的⼀个函数模板,本质内部是进⾏强制类型转换,将左值变为右值

cpp 复制代码
template <class _Ty>
remove_reference_t<_Ty>&& move(_Ty&& _Arg)
{ // forward _Arg as movable
	return static_cast<remove_reference_t<_Ty>&&>(_Arg);
}

变量表达式都是左值属性,也就意味着⼀个右值被右值引⽤绑定后,右值引⽤变量变量表达式的属性是左值

int b = 2; //2是右值,但b是左值

int&& c = 3; //3是右值,但c是左值
语法层⾯看,左值引⽤和右值引⽤都是取别名,不开空间。从汇编底层的⻆度看下⾯代码中r1和rr1
汇编层实现,底层都是⽤指针实现的

cpp 复制代码
#include<iostream>
using namespace std;
int main()
{
	// 左值:可以取地址
	// 以下的p、b、c、*p、s、s[0]就是常⻅的左值
	int* p = new int(0);
	int b = 1;
	const int c = b;
	*p = 10;
	string s("111111");
	s[0] = 'x';
	double x = 1.1, y = 2.2;

	// 左值引⽤给左值取别名
	int& r1 = b;
	int*& r2 = p;
	int& r3 = *p;
	string& r4 = s;
	char& r5 = s[0];

	// 右值引⽤给右值取别名
	int&& rr1 = 10;
	double&& rr2 = x + y;
	double&& rr3 = fmin(x, y);
	string&& rr4 = string("11111");
	// 左值引⽤不能直接引⽤右值,但是const左值引⽤可以引⽤右值
	const int& rx1 = 10;
	const double& rx2 = x + y;
	const double& rx3 = fmin(x, y);
	const string& rx4 = string("11111");
	// 右值引⽤不能直接引⽤左值,但是右值引⽤可以引⽤move(左值)
	int&& rrx1 = move(b);
	int*&& rrx2 = move(p);
	int&& rrx3 = move(*p);
	string&& rrx4 = move(s);
	string&& rrx5 = (string&&)s;

	// b、r1、rr1都是变量表达式,都是左值
	cout << &b << endl;
	cout << &r1 << endl;
	cout << &rr1 << endl;

	// 这⾥要注意的是,rr1的属性是左值,所以不能再被右值引⽤绑定,除⾮move⼀下
	int& r6 = r1;
	// int&& rrx6 = rr1;
	int&& rrx6 = move(rr1);
	return 0;
}

2.3延长生命周期

右值引⽤可⽤于为临时对象 延⻓⽣命周期 ,const 的左值引⽤也能延⻓临时对象⽣存期,但这些对象⽆法被修改

cpp 复制代码
int main()
{
	std::string s1 = "Test";

	// std::string&& r1 = s1; // 错误:不能绑定到左值
	const std::string& r2 = s1 + s1; 
    //const 的左值引⽤延⻓⽣存期
	// r2 += "Test"; // 错误:不能通过到 const 的引⽤修改

	std::string&& r3 = s1 + s1; // OK:右值引⽤延⻓⽣存期
	r3 += "Test"; // OK:能通过到⾮ const 的引⽤修改
	std::cout << r3 << '\n';
	return 0;
}

2.4左值和右值的参数匹配

C++98中,⼀个const左值引⽤作为参数的函数,那么实参传递左值和右值都可以匹配

C++11以后,分别重载左值引⽤、const左值引⽤、右值引⽤作为形参的f函数,那么实参是左值会

匹配f(左值引⽤),实参是const左值会匹配f(const 左值引⽤),实参是右值会匹配f(右值引⽤)。

需要强调,右值引⽤变量在⽤于表达式时属性是左值

cpp 复制代码
#include<iostream>
using namespace std;
void f(int& x)
{
	std::cout << "左值引⽤重载 f(" << x << ")\n";
}
void f(const int& x)
{
	std::cout << "到 const 的左值引⽤重载 f(" << x << ")\n";
}
void f(int&& x)
{
	std::cout << "右值引⽤重载 f(" << x << ")\n";
}
int main()
{
	int i = 1;
	const int ci = 2;
	f(i); // 调⽤ f(int&)
	f(ci); // 调⽤ f(const int&)
	f(3); // 调⽤ f(int&&),如果没有 f(int&&) 重载则会调⽤ f(const int&)
	f(std::move(i)); // 调⽤ f(int&&)
	// 右值引⽤变量在⽤于表达式时是左值
	int&& x = 1;
	f(x); // 调⽤ f(int& x)
	f(std::move(x)); // 调⽤ f(int&& x)
	return 0;
}

2.5右值引用和移动语义的使用场景

使用右值引用可以实现移动构造和移动赋值

2.5.1移动构造和移动赋值

移动构造函数是⼀种构造函数,类似拷⻉构造函数,移动构造函数要求第⼀个参数是该类类型的引
⽤,但是不同的是要求这个参数是右值引⽤,如果还有其他参数,额外的参数必须有缺省值
移动赋值是⼀个赋值运算符的重载,他跟拷⻉赋值构成函数重载,类似拷⻉赋值函数,移动赋值函
数要求第⼀个参数是该类类型的引⽤,但是不同的是要求这个参数是右值引⽤

对于像string/vector这样的深拷⻉的类或者包含深拷⻉的成员变量的类, 移动构造和移动赋值才有意义 ,因为移动构造和移动赋值的本质是要" 窃取 "引⽤的 右值对象的资源,提⾼效率,⽽不是像拷⻉构造和拷⻉赋值那样去拷⻉资源

演示移动构造和移动赋值:

cpp 复制代码
class string
{
public:
	string(const char* str = "")
		:_size(strlen(str))
		, _capacity(_size)
	{
		cout << "string(char* str)-构造" << endl;
		_str = new char[_capacity + 1];
		strcpy(_str, str);
	}
	string(const string& s)
		:_str(nullptr)
	{
		cout << "string(const string& s) -- 拷⻉构造" << endl;
		reserve(s._capacity);
		for (auto ch : s)
		{
			push_back(ch);
		}
	}
	// 移动构造
	string(string&& s)
	{
		cout << "string(string&& s) -- 移动构造" << endl;
		swap(s);
	}
	string& operator=(const string& s)
	{
		cout << "string& operator=(const string& s) -- 拷⻉赋值" <<
			endl;
		if (this != &s)
		{
			_str[0] = '\0';
			_size = 0;
			reserve(s._capacity);
			for (auto ch : s)
			{
				push_back(ch);
			}
		}
		return *this;
	}
	// 移动赋值
	string& operator=(string&& s)
	{
		cout << "string& operator=(string&& s) -- 移动赋值" << endl;
		swap(s);
		return *this;
	}
	~string()
	{
		cout << "~string() -- 析构" << endl;
		delete[] _str;
		_str = nullptr;
	}
private:
	char* _str = nullptr;
	size_t _size = 0;
	size_t _capacity = 0;
};

int main()

{

string s1("xxxxx");

// 拷⻉构造

string s2 = s1;

// 构造+移动构造,优化后直接构造

string s3 = bit::string("yyyyy");

// 移动构造

string s4 = move(s1);

cout << "******************************" << endl;

return 0;

}

注意:现在的编译器会在一些场景下会自行优化:

cpp 复制代码
namespace csl
{
	class string
	{
	public:
		typedef char* iterator;
		typedef const char* const_iterator;
		iterator begin()
		{
			return _str;
		}
		iterator end()
		{
			return _str + _size;
		}
		const_iterator begin() const
		{
			return _str;
		}
		const_iterator end() const
		{
			return _str + _size;
		}
		string(const char* str = "")
			:_size(strlen(str))
			, _capacity(_size)
		{
			cout << "string(char* str)-构造" << endl;
			_str = new char[_capacity + 1];
			strcpy(_str, str);
		}
		void swap(string& s)
		{
			::swap(_str, s._str);
			::swap(_size, s._size);
			::swap(_capacity, s._capacity);
		}
		string(const string& s)
			:_str(nullptr)
		{
			cout << "string(const string& s) -- 拷⻉构造" << endl;
			reserve(s._capacity);
			for (auto ch : s)
			{
				push_back(ch);
			}
		}
		string& operator=(const string& s)
		{
			cout << "string& operator=(const string& s) -- 拷⻉赋值" <<
				endl;
			if (this != &s)
			{
				_str[0] = '\0';
				_size = 0;
				reserve(s._capacity);
				for (auto ch : s)
				{
					push_back(ch);
				}
			}
			return *this;
		}
		~string()
		{
			cout << "~string() -- 析构" << endl;
			delete[] _str;
			_str = nullptr;
		}
		char& operator[](size_t pos)
		{
			assert(pos < _size);
			return _str[pos];
		}
		void reserve(size_t n)
		{
			if (n > _capacity)
			{
				char* tmp = new char[n + 1];
				if (_str)
				{
					strcpy(tmp, _str);
					delete[] _str;
				}
				_str = tmp;
				_capacity = n;
			}
		}
		void push_back(char ch)
		{
			if (_size >= _capacity)
			{
				size_t newcapacity = _capacity == 0 ? 4 : _capacity *
					2;
				reserve(newcapacity);
			}
			_str[_size] = ch;
			++_size;
			_str[_size] = '\0';
		}
		string& operator+=(char ch)
		{
			push_back(ch);
			return *this;
		}
		const char* c_str() const
		{
			return _str;
		}
		size_t size() const
		{
			return _size;
		}
	private:
		char* _str = nullptr;
		size_t _size = 0;
		size_t _capacity = 0;
	};
	string addStrings(string num1, string num2)
	{
		string str;
		int end1 = num1.size() - 1, end2 = num2.size() - 1;
		int next = 0;
		while (end1 >= 0 || end2 >= 0)
		{
			int val1 = end1 >= 0 ? num1[end1--] - '0' : 0;
			int val2 = end2 >= 0 ? num2[end2--] - '0' : 0;
			int ret = val1 + val2 + next;
			next = ret / 10;
			ret = ret % 10;
			str += ('0' + ret);
		}
		if (next == 1)
			str += '1';
		reverse(str.begin(), str.end());
		cout << "******************************" << endl;
		return str;
	}
}


int main()
{
	csl::string ret = csl::addStrings("11111", "22222");
	cout << ret.c_str() << endl;
	return 0;
}

完全不优化情况下应该是:

vs2022下会直接将str对象的构造,str拷⻉构造临时对象,临时对象拷⻉构造ret对象,合三为⼀,变为直接构造:

vs2022运行结果:

2.6类型分类

C++11以后,进⼀步对类型进⾏了划分,右值被划分纯右值和将亡值

纯右值:字⾯值常量、求值结果、临时对象

将亡值:返回右值引⽤的函数的调⽤表达式、转换为右值引⽤的转换函数的调⽤表达

2.7引用折叠

C++ 通过模板或 typedef 中的类型操作可以构成引⽤的引⽤
右值引⽤的右值引⽤ 折叠成 右值引⽤ ,所有 其他组合 均折叠成 左值引⽤

typedef int& lref;

typedef int&& rref;

int n = 0;

lref& r1 = n; // r1 的类型是 int&,左值引用

lref&& r2 = n; // r2 的类型是 int&,左值引用

rref& r3 = n; // r3 的类型是 int&,左值引用

rref&& r4 = 1; // r4 的类型是 int&&,右值引用

2.8完美转发

变量表达式都是左值属性,那么我们把 t 传递给下⼀层函数,那么匹配的都是左值引⽤版本的函数。想要保持t对象的属性,就需要使⽤ 完美转发 forward

cpp 复制代码
void Fun(int& x) { cout << "左值引用" << endl; }
void Fun(const int& x) { cout << "const 左值引用" << endl; }
void Fun(int&& x) { cout << "右值引用" << endl; }
void Fun(const int&& x) { cout << "const 右值引用" << endl; }
template<class T>

void Function(T&& t)
{
	Fun(t);
	//Fun(forward<T>(t));  //使用完美转发
}

int main()
{	
	Function(10); // 右值
	int a;
	Function(a); // 左值
	Function(std::move(a)); // 右值
	const int b = 8;
	Function(b); // const 左值
	Function(std::move(b)); // const 右值
	return 0;
}

完美转发的本质就是函数模板

template <class _Ty>

_Ty&& forward(remove_reference_t<_Ty>& _Arg) noexcept

{

return static_cast<_Ty&&>(_Arg);

}

3.可变参数模板

可变参数模板,也就是说⽀持可变数量参数的函数模板和类模板
可变数目的参数被称为参数包,存在两种参数包:模板参数包、函数参数包

template <class ...Args> void Func(Args... args) {}
template <class ...Args> void Func(Args&... args) {}
template <class ...Args> void Func(Args&&... args) {}
⽤省略号来指出⼀个模板参数或函数参数的表⽰⼀个包,在模板参数列表中,class...或 typename...指出接下来的参数表⽰零或多个类型列表;在函数参数列表中,类型名后⾯跟...指出
接下来表⽰零或多个形参对象列表;函数参数包可以⽤左值引⽤或右值引⽤表⽰,跟前⾯普通模板
⼀样,每个参数实例化时遵循引⽤折叠规则
sizeof...计算参数包中参数的个数:

cpp 复制代码
#include<iostream>
using namespace std;

template <class ...Args>
void Print(Args&&... args)
{
	cout << sizeof...(args) << endl;
}
int main()
{
	double x = 2.2;
	Print(); // 包⾥有0个参数
	Print(1); // 包⾥有1个参数
	Print(1, string("xxxxx")); // 包⾥有2个参数
	Print(1.1, string("xxxxx"), x); // 包⾥有3个参数
	return 0;
}

3.1包扩展

当扩展⼀个包时,要提供⽤于每个扩展元素的模式
扩展⼀个包就是将它分解为构成的元素,对每个元素应⽤模式,获得扩展后的列表

cpp 复制代码
void ShowList()
{
	// 编译器时递归的终⽌条件,参数包是0个时,直接匹配这个函数
	cout << endl;
}
template <class T, class ...Args>
void ShowList(T x, Args... args)
{
	cout << x << " ";
	// args是N个参数的参数包
	// 调⽤ShowList,参数包的第⼀个传给x,剩下N-1传给第⼆个参数包
	ShowList(args...);
}
// 编译时递归推导解析参数
template <class ...Args>
void Print(Args... args)
{
	ShowList(args...);
}
int main()
{
	Print();
	Print(1);
	Print(1, string("xxxxx"));
	Print(1, string("xxxxx"), 2.2);
	return 0;
}

编译时的细节:

3.2 emplace系列接口

C++11以后STL容器新增了empalce系列的接⼝,均为 模板可变参数 ,功能上兼容push和insert系列
假设容器为container<T>,empalce还⽀持直接插⼊构造T对象的参数,有些场景会更⾼效⼀些,
可以直接在容器空间上构造T对象,使用与insert、push类似

4. lambda

lambda 表达式本质是⼀个 匿名函数对象 ,跟普通函数不同的是他可以定义在函数内部。
lambda 表达式语法使⽤层⽽⾔没有类型,⼀般是⽤auto或者模板参数定义的对象去接收lambda 对象

4.1 lambda语法

lambda的语法:

capture-list\] (parameters) -\> return type { function boby }

lambda是一个匿名函数对象,它与函数有相似之处,也有不同:

capture-list\]:捕捉列表,能够捕捉上下⽂中的变量供 lambda 函数使用 (parameters) :参数列表,如果不需要参数传递,则可以连 同()⼀起省略 -\>return type :返回值类型,⽤追踪返回类型形式声明函数的返回值类型,没有返回值时此部分可省略 {function boby} :函数体,跟普通函数完全类似,在该函数体内,还可以使⽤所有捕获到的变量,任何时候花括号{}都不能省略 ```cpp int main() { // ⼀个简单的lambda表达式 auto add1 = [](int x, int y)->int {return x + y; }; cout << add1(2, 2) << endl; // 1、捕捉为空也不能省略 // 2、参数为空可以省略 // 3、返回值可以省略,可以通过返回对象⾃动推导 // 4、函数题不能省略 auto func1 = [] { cout << "lambda" << endl; return 0; }; func1(); int a = 0, b = 1; auto swap1 = [](int& x, int& y) { int tmp = x; x = y; y = tmp; }; swap1(a, b); cout << a << ":" << b << endl; return 0; } ``` ### 4.2 lambda的应用 lambda可用于调用对象,相比于函数指针和仿函数对象,lambda更方便;还可用于线程中定义线程的执⾏函数逻辑,智能指针中定制删除器等 下面为lambda在比较大小的使用: ```cpp #include #include #include #include using namespace std; struct Goods { string _name; // 名字 double _price; // 价格 int _evaluate; // 评价 // ... Goods(const char* str, double price, int evaluate) :_name(str) , _price(price) , _evaluate(evaluate) {} }; //仿函数 struct ComparePriceLess { bool operator()(const Goods& gl, const Goods& gr) { return gl._price < gr._price; } }; //仿函数 struct ComparePriceGreater { bool operator()(const Goods& gl, const Goods& gr) { return gl._price > gr._price; } }; int main() { vector v = { { "手机", 2.1, 5 }, { "手表", 3, 4 }, { "相机", 2.2, 3}, { "平板", 1.5, 4 } }; // 类似这样的场景,我们实现仿函数对象或者函数指针支持商品中 // 不同项的比较,相对还是⽐较麻烦的,那么这里lambda就很好用了 sort(v.begin(), v.end(), ComparePriceLess()); sort(v.begin(), v.end(), ComparePriceGreater()); //lambda //价格升序 sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) { return g1._price < g2._price;}); //价格降序 sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) { return g1._price > g2._price;}); //评价升序 sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) { return g1._evaluate < g2._evaluate;}); //评价降序 sort(v.begin(), v.end(), [](const Goods& g1, const Goods& g2) { return g1._evaluate > g2._evaluate;}); return 0; } ``` ## 5.包装器 ### 5.1 function > template \< class T \> > class function ; std::function是一个类模板,也是一个包装器,被包含在\这个头⽂件中,实例化出的对象可以存储其他的可以调⽤对象,包括函数指针、仿函数、lambda 、bind 表达式等 函数指针、仿函数、 lambda 等可调⽤对象的类型各不相同, std::function 的优势就是统⼀类型,对他们都可以进⾏包装,这样在很多地⽅就⽅便声明可调⽤对象的类型 ```cpp #include int f(int a, int b) { return a + b; } struct Functor { public: int operator() (int a, int b) { return a + b; } }; class Plus { public: Plus(int n = 100) :_n(n) {} static int plusi(int a, int b) { return a + b; } double plusd(double a, double b) { return (a + b) * _n; } private: int _n; }; int main() { // 包装各种可调用对象 function f1 = f; function f2 = Functor(); function f3 = [](int a, int b) {return a + b; }; cout << f1(1, 1) << endl; cout << f2(1, 1) << endl; cout << f3(1, 1) << endl; // 包装静态成员函数 // 成员函数要指定类域并且前⾯加&才能获取地址 function f4 = &Plus::plusi; cout << f4(1, 1) << endl; // 包装普通成员函数 // 普通成员函数还有⼀个隐含的this指针参数,所以绑定时传对象或者对象的指针过去都可以 function f5 = &Plus::plusd; Plus pd; cout << f5(&pd, 1.1, 1.1) << endl; function f6 = &Plus::plusd; cout << f6(pd, 1.1, 1.1) << endl; cout << f6(pd, 1.1, 1.1) << endl; function f7 = &Plus::plusd; cout << f7(move(pd), 1.1, 1.1) << endl; cout << f7(Plus(), 1.1, 1.1) << endl; return 0; } ``` ### 5.2 bind bind 是⼀个 函数模板 ,也是⼀个可调⽤对象的 包装器 ,被包含在\这个头⽂件中。可以把他看做⼀个函数适配器,对接收的fn可调⽤对象进⾏处理后返回⼀个可调⽤对象,bind 可以⽤来调整参数个数和参数顺序 调⽤bind的⼀般形式: auto newCallable = bind(callable,arg_list), newCallable 是⼀个 可调⽤对象 , arg_list 是⼀个 参数列表 ,对应给定的callable的参数。当我们调⽤newCallable时newCallable会调⽤callable,并传给它arg_list中的参数 arg_list中的参数可能包含形如_n的名字,并且依次类推,_1,_2, _3... ```cpp #include using placeholders::_1; using placeholders::_2; using placeholders::_3; int Sub(int a, int b) { return (a - b) * 10; } int SubX(int a, int b, int c) { return (a - b - c) * 10; } class Plus { public: static int plusi(int a, int b) { return a + b; } double plusd(double a, double b) { return a + b; } }; int main() { auto sub1 = bind(Sub, _1, _2); cout << sub1(10, 5) << endl; // bind 本质返回的⼀个仿函数对象 // 调整参数顺序(不常⽤) // _1代表第⼀个实参 // _2代表第⼆个实参 // ... auto sub2 = bind(Sub, _2, _1); cout << sub2(10, 5) << endl; // 调整参数个数 auto sub3 = bind(Sub, 100, _1); cout << sub3(5) << endl; auto sub4 = bind(Sub, _1, 100); cout << sub4(5) << endl; // 分别绑死第123个参数 auto sub5 = bind(SubX, 100, _1, _2); cout << sub5(5, 1) << endl; auto sub6 = bind(SubX, _1, 100, _2); cout << sub6(5, 1) << endl; auto sub7 = bind(SubX, _1, _2, 100); cout << sub7(5, 1) << endl; // 成员函数对象进⾏绑死,就不需要每次都传递了 function f6 = &Plus::plusd; Plus pd; cout << f6(move(pd), 1.1, 1.1) << endl; cout << f6(Plus(), 1.1, 1.1) << endl; // bind⼀般用于,绑死⼀些固定参数 function f7 = bind(&Plus::plusd, Plus(), _1, _2); cout << f7(1.1, 1.1) << endl; return 0; } ```

相关推荐
Elias不吃糖2 小时前
NebulaChat:C++ 高并发聊天室服务端
开发语言·c++·redis·sql·项目文档
帅中的小灰灰2 小时前
C++编程策略设计模式
开发语言·c++·设计模式
是小胡嘛3 小时前
华为云CentOS系统中运行http服务器无响应
linux·服务器·c++·http·centos·华为云
福尔摩斯张3 小时前
C语言核心:string函数族处理与递归实战
c语言·开发语言·数据结构·c++·算法·c#
江澎涌4 小时前
JHandler——一套简单易用的 C++ 事件循环机制
android·c++·harmonyos
liu****4 小时前
5.C语言数组
c语言·开发语言·c++
毛甘木4 小时前
Unity MonoPInvokeCallback 使用教程
c++·unity
吗~喽4 小时前
【LeetCode】滑动窗口_水果成篮_C++
c++·算法·leetcode
BestOrNothing_20155 小时前
【C++基础】Day 4:关键字之 new、malloc、constexpr、const、extern及static
c++·八股文·static·extern·new与malloc·constexpr与const