c++11 中的函数回调方式

#include <functional>
#include <iostream>

void print_num(int i);

inline void print_num(int i)
{
std::cout << i << '\n';
}

struct PrintNum {
void operator()(int i) const
{
std::cout << i << '\n';
}
};

struct Foo {
Foo(int num) : num_(num) {}
void print_add(int i) const { std::cout << num_ + i << '\n'; }
int num_;
};

void main()
{
// store a free function // 存储自由函数
std::function<void(int)> f_display = print_num;
f_display(-9);

// store a lambda //存储lambda表达式
std::function<void()> f_display_42 = []() { print_num(42); };
f_display_42();

//store the result of a call to std::bind //存储std::bind 结果
std::function<void()> f_display_31337 = std::bind(print_num, 31337);
f_display_31337();

// 类实例
const Foo foo(314159);
// store a call to a member function and object //存储类成员方法和类实例
using std::placeholders::_1;
std::function<void(int)> f_add_display2 = std::bind(&Foo::print_add, foo, _1);
f_add_display2(2);

// store a call to a member function and object ptr ////存储类成员方法和类实例指针
std::function<void(int)> f_add_display3 = std::bind(&Foo::print_add, &foo, _1);
f_add_display3(3);

// store a call to a function object //存储结构体方法//仿函数
std::function<void(int)> f_display_obj = PrintNum();
f_display_obj(18);
}

 

posted @ 2021-01-21 16:28  Ray.floyd  阅读(388)  评论(0编辑  收藏  举报