std和boost的function与bind实现剖析
用过std和boost的function对象和bind函数的童鞋们都知道这玩意用起来腰不酸了,腿不疼了,心情也舒畅了。先上一个简单得示例:
std::string str;
std::function func = std::bind(&std::string::at, &str);
bool is_empty = func(); 但是这是怎么做到的呢?看完源码以后,你会发现这里面有着一些很巧妙的设计。
用过std和boost的function对象和bind函数的童鞋们都知道这玩意用起来腰不酸了,腿不疼了,心情也舒畅了。先上一个简单得示例:
std::string str;
std::function func = std::bind(&std::string::at, &str);
bool is_empty = func(); 但是这是怎么做到的呢?看完源码以后,你会发现这里面有着一些很巧妙的设计。
绑定函数是我认为C++新标准里第二有用的库了 绑定库的使用环境是:
先来看一段代码
#include
#include
#include
#include
class button
{
public:
std::function onClick;
};
class player
{
public:
void play(void* sender, int param) {
printf("Play: %d => %d\n", (int)sender, param);
};
void stop(void* sender, int param) {
printf("Play: %d => %d\n", (int)sender, param);
};
};
button playButton, stopButton;
player thePlayer;
void connect()
{
playButton.onClick = std::bind(&player::play, &thePlayer, &playButton, std::placeholders::_1);
stopButton.onClick = std::bind(&player::stop, &thePlayer, &stopButton, std::placeholders::_1);
}
int main () {
connect();
playButton.onClick(0);
return 0;
}
// 以上代码参考boost中bind库示例代码,在G++ 4.6.1中测试通过 木有错,这是C++,并且很方便地实现了委托 这就是传说中的绑定库和增强型的函数对象 接下来一个一个来