C++11 std::function用法
直接上代码:
例子1:std::function的感觉就像是函数指针那样有木有
#include <iostream>
#include <functional>
#include <map>
using namespace std;
// 普通函数
int add(int i, int j) { return i + j; }
//lambda表达式
auto mod = [](int i, int j){return i % j; };
// 函数对象类
struct divide
{
int operator() (int denominator, int divisor)
{
return denominator / divisor;
}
};
void main()
{
// 更灵活的map
map<char, function<int(int, int)>> binops;
binops['+'] = add;
binops['-'] = minus<int>();
binops['*'] = [](int i, int j){return i * j; };
binops['/'] = divide();
binops['%'] = mod;
cout << binops['+'](10, 5) << endl;
cout << binops['-'](10, 5) << endl;
cout << binops['*'](10, 5) << endl;
cout << binops['/'](10, 5) << endl;
cout << binops['%'](10, 5) << endl;
system("pause");
}
上面代码同时简单介绍了“Lambda 表达式”,“Lambda 表达式”(lambda expression)是一个匿名函数,Lambda表达式基于数学中的λ演算得名,直接对应于其中的lambda抽象(lambda abstraction),是一个匿名函数,即没有函数名的函数。Lambda表达式可以表示闭包(注意和数学传统意义上的不同)。
C++11 std::bind用法
例子2:
std::bind的使用...std::bind更像是对一个已有的函数进行一次包装(装饰)
#include <iostream>
#include <functional>
#include <typeinfo>
#include <string>
using namespace std;
int add1(int i, int j, int k) {
return i + j + k;
}
class Person {
public:
Person (const char* name):m_strName(name) {}
void sayHello(const char* name) const {
std::cout << m_strName<< " say: hello " << name << std::endl;
}
int operator()(int i, int j, int k) const {
return i + j + k;
}
static string getClassName()
{
return string("Person");
}
private:
string m_strName;
};
/*
*
*/
int main(void) {
// 绑定全局函数
auto add2 = std::bind(add1, std::placeholders::_1, std::placeholders::_2, 10);
// 函数add2 = 绑定add1函数,参数1不变,参数2不变,参数3固定为10.
std::cout << typeid(add2).name() << std::endl;
std::cout << "add2(1,2) = " << add2(1, 2) << std::endl;
std::cout << "\n---------------------------" << std::endl;
// 绑定成员函数
Person man("std::function");
auto sayHello = std::bind(&Person::sayHello, man/*调用者*/, std::placeholders::_1/*参数1*/);
sayHello("Peter");
auto sayHelloToPeter = std::bind(&Person::sayHello, man/*调用者*/, "Peter"/*固定参数1*/);
sayHelloToPeter ();
// 绑定静态成员函数
auto getClassName= std::bind(&Person::getClassName);
std::cout << getClassName() << std::endl;
std::cout << "\n---------------------------" << std::endl;
// 绑定operator函数
auto add100 = std::bind(&Person::operator (), man, std::placeholders::_1, std::placeholders::_2, 100);
std::cout << "add100(1, 2) = " << add100(1, 2) << std::endl;
// 注意:无法使用std::bind()绑定一个重载函数
system("pause");
return 0;
}