hello~ 很高兴见到大家! 这次带来的是C++中关于C++11这部分的一些知识点,如果对你有所帮助的话,可否留下你宝贵的三连呢? 个 人 主 页: 默|笙

接上次的博客<C++11(二)可变参数模板、emplace系列接口、默认的移动构造和移动赋值>
[capture_list] (parameters) -> return type { function boby };auto add = [](int x, int y)->int { return x + y; };
int n = add(1, 2);
cout << n << endl;

int a = 1, b = 2;
auto add = [a, &b]()mutable { a = 2; b = 5; };
add();
cout << a << " " << b << endl;
auto add = [a, &b]()mutable { a = 2; b = 5; };
class 类名//类名由编译器生成
{
public:
类名(int a, int& b)
:_a(a)
,_b(b)
{}
void operator()()//如果没有mutable,后面加上const
{
_a = 2;
_b = 5;
}
private:
int _a;
int& _b;
};
#include<functional>
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 = 10)
:_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<int(int, int)> f1 = f;
function<int(int, int)> f2 = Functor();
function<int(int, int)> f3 = [](int a, int b) {return a + b; };
//包装静态成员函数,成员函数需要指定类域且前面加&才能获取地址
function<int(int, int)> f4 = &Plus::plusi;
//不过静态成员函数前面可以不加&,但是推荐加
function<int(int, int)> f5 = Plus::plusi;
//包装普通类成员函数,不要忘了成员函数的第一个参数是this指针。
Plus obj;
//传递对象指针-最常用的方式
function<double(Plus*, double, double)> f6 = &Plus::plusd;
double r1 = f6(&obj, 1.1, 2.2);//传递地址
//传递对象--有拷贝
function<double(Plus, double, double)> f7 = &Plus::plusd;
double r2 = f7(obj, 1.1, 2.2);
//传递右值引用
function<double(Plus&&, double, double)> f8 = &Plus::plusd;
double r3 = f8(move(obj), 1.1, 2.2);
//传递左值引用
function<double(Plus&, double, double)> f9 = &Plus::plusd;
double r4 = f9(obj, 1.1, 2.2);
return 0;
}#include<functional>
using placeholders::_1;
using placeholders::_2;
using placeholders::_3;
int Sub(int a, int b)
{
return a - b;
}
int main()
{
cout << Sub(5, 10) << endl;
auto newSub1 = bind(Sub, _2, _1);
cout << newSub1(5, 10) << endl;
auto newSub2 = bind(Sub, 5, _1);
cout << newSub2(10) << endl;
return 0;
}

今天的分享就到此结束啦,如果对读者朋友们有所帮助的话,可否留下宝贵的三连呢~~ 让我们共同努力, 一起走下去!