【C++11(二)】可变参数模板和 lambda表达式
1.可变参数模板
C++11 的新特性可变参数模板能够让我们创建可以接受可变参数的函数模板和类模板,相比 C++98/03 ,类模版和函数模版中只能含固定数量的模版参数,可变模版参数是一个巨大的改进。
例如 printf 函数,这个是函数的可变参数如下图:

… 代表可以传任意个参数。
可变参数模板的语法:
// Args是一个模板参数包,args是一个函数形参参数包
// 声明一个参数包Args...args,这个参数包中可以包含0到任意个模板参数。
template <class ...Args>
void ShowList(Args... args)
{
cout << sizeof...(args) << endl;//可以通过 sizeof...(args) 计算出参数包的个数
}
可以像以下这样传参:
int main()
{
ShowList(1, 2, 3, 4, 5);
ShowList(1, "abcde", 3.33);
return 0;
}
计算结果如下:

我们无法直接获取参数包 args 中的每个参数的,只能通过展开参数包的方式来获取参数包中的每个参数,这是使用可变模版参数的一个主要特点,也是最大的难点,即如何展开可变模版参数。由于语法不支持使用 args[i] 这样方式获取可变参数,所以我们的用一些其他方式来逐个获取参数包的值。
1.1 递归函数方式展开参数包
// 递归终止函数
void _ShowList()
{
cout << endl;
}
// 展开函数
template <class T, class ...Args>
void _ShowList(const T& val, Args... args)
{
cout << val << " ";
_ShowList(args...);
}
template <class ...Args>
void ShowList(Args... args)
{
_ShowList(args...);
}
int main()
{
ShowList(1, 2, 3, 4, 5);
ShowList(1, "abcde", 3.33);
return 0;
}

这种方法叫做编译时的递归推演。
1.2 逗号表达式展开参数包
这种展开参数包的方式,不需要通过递归终止函数,是直接在expand函数体中展开的。
PrintArg 不是一个递归终止函数,只是一个处理参数包中每一个参数的函数。
template <class T>
int PrintArg(T t)
{
cout << t << " ";
return 0;
}
//展开函数
template <class ...Args>
void ShowList(Args... args)
{
int arr[] = { PrintArg(args)... };
cout << endl;
}
初始化 arr,就强行让编译器解析参数包,参数包有几个参数,PrintArg 就依次推演生成几个参数。

1.3 STL容器中的 empalce 相关接口函数
C++11中为容器新增了一些 empalce 的插入接口,首先我们看到的 emplace 系列的接口,支持模板的可变参数,并且万能引用。那么相对 insert 和 emplace 系列接口的优势到底在哪里呢?


之前模拟实现的有移动语义的string:
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <assert.h>
#include <algorithm>
#include<list>
using namespace std;
namespace Raja
{
class string
{
public:
typedef char* iterator;
iterator begin()
{
return _str;
}
iterator end()
{
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);
}
// s1.swap(s2)
void swap(string& s)
{
::swap(_str, s._str);
::swap(_size, s._size);
::swap(_capacity, s._capacity);
}
// 移动构造
string(string&& s)
:_str(nullptr)
, _size(0)
, _capacity(0)
{
cout << "string(string&& s) -- 移动构造" << endl;
swap(s);
}
// 移动赋值
string& operator=(string&& s)
{
cout << "string& operator=(string&& s) -- 移动语义" << endl;
swap(s);
return *this;
}
// 拷贝构造
string(const string& s)
:_str(nullptr)
{
cout << "string(const string& s) -- 深拷贝" << endl;
string tmp(s._str);
swap(tmp);
}
// 赋值重载
string& operator=(const string& s)
{
cout << "string& operator=(string s) -- 深拷贝" << endl;
string tmp(s);
swap(tmp);
return *this;
}
~string()
{
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];
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)
string& operator+=(char ch)
{
push_back(ch);
return *this;
}
const char* c_str() const
{
return _str;
}
static string to_string(int x)
{
Raja::string ret;
while (x)
{
int val = x % 10;
x /= 10;
ret += ('0' + val);
}
reverse(ret.begin(), ret.end());
return ret;
}
private:
char* _str;
size_t _size;
size_t _capacity; // 不包含最后做标识的\0
};
}
使用两种方法插入一些数据,如下:
int main()
{
list<Raja::string> lt;
Raja::string s1("abcde");
lt.push_back(s1);
lt.push_back(move(s1));
Raja::string s2("edcba");
lt.emplace_back(s2);
lt.emplace_back(move(s2));
return 0;
}

我们发现,在这种情况下两者并没有明显的区别,那么它们的区别到底在哪呢?
下面我们换一种初始化方式,我们在构造函数中也打印相应的语句,这样有利于我们观察:
int main()
{
list<Raja::string> lt;
lt.push_back("abcde");
lt.emplace_back("abcde");
return 0;
}

成员类型 value_type 是容器中元素的类型,列表中定义为其第一个模板参数(T)的别名。

结论:emplace_back 比 push_back 略微高效一点点,并没有很大的提升,因为移动构造的成本也是足够低的
2. lambda表达式
2.1 C++98 中的一个例子
在 C++98 中,如果想要对一个数据集合中的元素进行排序,可以使用std::sort 方法:
int main()
{
int array[] = { 4,1,8,5,3,7,0,9,2,6 };
// 默认按照小于比较,排出来结果是升序
std::sort(array, array + sizeof(array) / sizeof(array[0]));
// 如果需要降序,需要改变元素的比较规则
std::sort(array, array + sizeof(array) / sizeof(array[0]), greater<int>());
return 0;
}
如果待排序元素为自定义类型,需要用户定义排序时的比较规则,所以这时候需要写仿函数:
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;
}
};
其中,sort 中的 Compare comp 是一个可调用对象:

随着 C++ 语法的发展,人们开始觉得上面的写法太复杂了,每次为了实现一个算法。都要重新去写一个类,如果每次比较的逻辑不一样,还要去实现多个类,特别是相同类的命名,这些都给编程者带来了极大的不便。因此,在 C++11 语法中出现了 lambda 表达式。
2.2 使用 lambda 表达式
如果想使用 lambda 表达式达到上面的比较效果,假设我们需要分别写一个按照商品的价格的高低的排序,如下:
struct Goods
{
string _name; // 名字
double _price; // 价格
int _evaluate; // 评价
Goods(const char* str, double price, int evaluate)
: _name(str)
, _price(price)
, _evaluate(evaluate)
{}
};
int main()
{
vector<Goods> v = { { "苹果", 2.1, 5 }, { "香蕉", 3, 4 },
{ "橙子", 2.2,3 }, { "菠萝", 1.5, 4 } };
// 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; });
return 0;
}
上述代码就是使用 C++11 中的 lambda 表达式来解决,可以看出 lambda 表达式实际是一个匿名函数。
2.3 lambda 表达式语法
[capture-list] (parameters) mutable -> return-type { statement };
(1)表达式各部分说明:
- [capture-list] : 捕捉列表,该列表总是出现在 lambda 函数的开始位置,编译器根据[]来判断接下来的代码是否为 lambda 函数,捕捉列表能够捕捉上下文中的变量供 lambda 函数使用。
- (parameters):参数列表。与普通函数的参数列表一致,如果不需要参数传递,则可以连同()一起省略
- mutable:默认情况下,lambda 函数总是一个 const 函数,mutable 可以取消其常量性。使用该修饰符时,参数列表不可省略(即使参数为空)。现阶段我们按照默认的使用即可,可省略。
- ->returntype:返回值类型。用追踪返回类型形式声明函数的返回值类型,没有返回值时此部分可省略。返回值类型明确情况下,也可省略,由编译器对返回类型进行推导。
- {statement}:函数体。在该函数体内,除了可以使用其参数外,还可以使用所有捕获到的变量。
捕捉列表和函数体是必须写的,其它的可省略。
因此 C++11 中最简单的 lambda 函数为:[]{}; 该 lambda 函数不能做任何事情。
由于 lambda 表达式是一个可调用对象,所以也可以像下面一样写:
int main()
{
auto f1 = [](int x) {cout << x << endl; return 0; };
f1(10);
return 0;
}

lambda 表达式的类型是一个类,这个类的名称是 lambda + uuid. 每个 lambda 都会生成一个类
(2)捕获列表说明
捕捉列表描述了上下文中哪些数据可以被 lambda 使用,以及使用的方式传值还是传引用。
- [var]:表示值传递方式捕捉变量 var
- [=]:表示值传递方式捕获所有父作用域中的变量(包括this)
- [&var]:表示引用传递捕捉变量 var
- [&]:表示引用传递捕捉所有父作用域中的变量(包括this)
- [this]:表示值传递方式捕捉当前的 this 指针
注意:
- 父作用域指包含 lambda 函数的语句块;
- 语法上捕捉列表可由多个捕捉项组成,并以逗号分割。
比如:
[=, &a, &b]:以引用传递的方式捕捉变量 a 和 b,值传递方式捕捉其他所有变量;
[&,a, this]:值传递方式捕捉变量 a 和 this,引用方式捕捉其他变量; - 捕捉列表不允许变量重复传递,否则就会导致编译错误。
比如:[=, a]:=已经以值传递方式捕捉了所有变量,捕捉 a 重复; - 在块作用域以外的 lambda 函数捕捉列表必须为空;
- 在块作用域中的 lambda 函数仅能捕捉父作用域中局部变量,捕捉任何非此作用域或者非局部变量都会导致编译报错;
- lambda 表达式之间不能相互赋值,即使看起来类型相同。
2.4 函数对象与 lambda 表达式
函数对象,又称为仿函数,即可以像函数一样使用的对象,就是在类中重载了 operator() 运算符的类对象。
如下分别为仿函数和 lambda:
class Rate
{
public:
Rate(double rate)
: _rate(rate)
{}
double operator()(double money, int year)
{
return money * _rate * year;
}
private:
double _rate;
};
int main()
{
// 函数对象
double rate = 0.49;
Rate r1(rate);
r1(10000, 2);
// lambda
auto r2 = [=](double monty, int year) {return monty * rate * year; };
r2(10000, 2);
return 0;
}
从使用方式上来看,函数对象与 lambda 表达式完全一样。
函数对象将 rate 作为其成员变量,在定义对象时给出初始值即可,lambda 表达式通过捕获列表可以直接将该变量捕获到。
实际在底层编译器对于 lambda 表达式的处理方式,完全就是按照函数对象的方式处理的,即:如果定义了一个 lambda 表达式,编译器会自动生成一个类,在该类中重载了 operator()。
3.包装器
function 包装器 也叫作适配器,C++ 中的 function 本质是一个类模板。
包装器包装的是什么?其实包装器包装的是可调用对象,目前我们学习到的可调用对象有:函数指针、仿函数、lambda,我们要学的包装器就是要包装它们三个中的任意一个。
函数指针的设计不太好,不符合我们常规的写法,例如:void (pswap)(int p1, int* p2),这种方式不好写,类型也不好写。
仿函数类型比较好写,但是它比较重,它得在全局里面单独定义一个类,即使是写一个很简单的比较,也是需要定义一个类,这种方法太笨重了。
而 lambda 比较灵活,但是 lambda 也和函数指针面临同样的问题,类型不好写,类型是匿名的。
function 包装器的语法:
// 类模板原型如下
template <class Ret, class... Args>
class function<Ret(Args...)>;
//模板参数说明:
//Ret: 被调用函数的返回类型
//Args…:被调用函数的形参
使用一下包装器包装可调用对象,假设我们需要包装一个实现两个数交换的可调用对象,如下,先包装函数指针:
void swap_func(int& x, int& y)
{
int tmp = x;
x = y;
y = tmp;
}
int main()
{
int x = 10, y = 20;
cout << "x = " << x << " " << "y = " << y << endl;
// 包装函数指针
function<void(int&, int&)> f1 = swap_func;
f1(x, y);
cout << "x = " << x << " " << "y = " << y << endl;
return 0;
}

完成了对函数指针的包装。
包装函数对象和 lambda:
void swap_func(int& x, int& y)
{
int tmp = x;
x = y;
y = tmp;
}
class Swap
{
public:
void operator() ( int& x, int& y )const
{
int tmp = x;
x = y;
y = tmp;
}
};
int main()
{
int x = 10, y = 20;
cout << "x = " << x << " " << "y = " << y << endl;
auto swap_lambda = [](int& r1, int& r2)
{
int tmp = r1;
r1 = r2;
r2 = tmp;
};
// 包装函数指针
function<void(int&, int&)> f1 = swap_func;
f1(x, y);
cout << "x = " << x << " " << "y = " << y << endl;
// 包装函数对象
function<void(int&, int&)> f2 = Swap();
f2(x, y);
cout << "x = " << x << " " << "y = " << y << endl;
// 包装 lambda
function<void(int&, int&)> f3 = swap_lambda;
f3(x, y);
cout << "x = " << x << " " << "y = " << y << endl;
return 0;
}

但是在实际中我们并不像上面的这样用,假设我们需要将可调用对象放入一个容器中,假设是 map,就可以像下面这样包装:
map<string, function<void(int&, int&)>> cmdOP = {
{"函数指针", swap_func},{"仿函数", Swap()},{"lambda", swap_lambda}};
在使用的时候,就像在使用对应的命令去调对应的函数一样,这就是回调
void swap_func(int& x, int& y)
{
int tmp = x;
x = y;
y = tmp;
}
class Swap
{
public:
void operator() (int& x, int& y)const
{
int tmp = x;
x = y;
y = tmp;
}
};
int main()
{
int x = 10, y = 20;
cout << "x = " << x << " " << "y = " << y << endl << endl;
auto swap_lambda = [](int& r1, int& r2)
{
int tmp = r1;
r1 = r2;
r2 = tmp;
};
map<string, function<void(int&, int&)>> cmdOP = {
{"函数指针", swap_func},
{"仿函数", Swap()},
{"lambda", swap_lambda}
};
cmdOP["函数指针"](x, y);
cout << "x = " << x << " " << "y = " << y << endl;
cmdOP["仿函数"](x, y);
cout << "x = " << x << " " << "y = " << y << endl;
cmdOP["lambda"](x, y);
cout << "x = " << x << " " << "y = " << y << endl;
return 0;
}

1621

被折叠的 条评论
为什么被折叠?



