C++ 新特性学习(四) — Bind和Function
#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* 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中测试通过Bind
函数使用形式:
绑定组合
Function
使用形式
std::function和函数指针的优劣
性能
Last updated
Was this helpful?