std和boost的function与bind实现剖析
用过std和boost的function对象和bind函数的童鞋们都知道这玩意用起来腰不酸了,腿不疼了,心情也舒畅了。先上一个简单得示例:
std::string str;
std::function<bool()> func = std::bind(&std::string::at, &str);
bool is_empty = func();但是这是怎么做到的呢?看完源码以后,你会发现这里面有着一些很巧妙的设计。
用过std和boost的function对象和bind函数的童鞋们都知道这玩意用起来腰不酸了,腿不疼了,心情也舒畅了。先上一个简单得示例:
std::string str;
std::function<bool()> func = std::bind(&std::string::at, &str);
bool is_empty = func();但是这是怎么做到的呢?看完源码以后,你会发现这里面有着一些很巧妙的设计。
绑定函数是我认为C++新标准里第二有用的库了 绑定库的使用环境是:
先来看一段代码
#include <iostream>
#include <cstdio>
#include <memory>
#include <functional>
class button
{
public:
std::function<void(int)> onClick;
};
class player
{
public:
void play(void* sender, int param) {
printf("Play: %d => %d\n", (int)sender, param);
};
void stop(void*…