C++实现回调函数 funtor
来源:互联网 发布:哈工大 人工智能 教授 编辑:程序博客网 时间:2024/06/05 12:47
在C语言中,使用函数指针很容易实现回调函数,回调函数把调用者和被调用者在代码中分开。而在C++中,如果想用函数指针调用一个实例的非static方法没那么容易,因为实际上在调用对象的非静态方法时,编译器会把this指针加入该方法的参数列表了。 C++中实现回调函数可以使用funtor的方法。以下是转自http://www.devx.com/tips/Tip/27126
Use Functor for Callbacks in C++
Using the callback function in C is pretty straightforward, but in C++ it becomes little tricky. If you want to use a member function as a callback function, then the member function needs to be associated with an object of the class before it can be called. In this case, you can use functor. Suppose you need to use the member function get() of the class base as a callback function
class base {
public: int get () { return 7;}
};
Then, you need to define a functor:
class CallbackFunctor {
functor(const base& b):m_base(b) {}
int operator() () {
return m_base.get();
}
};
Now you can use an object of CallbackFunctor as a callback function as follows. Define the function that needs a callback to take an argument of type CallbackFunctor:
void call (CallbackFunctor& f) {
cout << f() << endl;
}
int main () {
base b;
functor f(b);
call(f);
}
- C++实现回调函数 funtor
- 回调函数 c实现
- 回调函数实现例子-c语言
- c语言实现回调函数
- C 回调函数
- 【c++】回调函数
- C 回调函数
- C回调函数
- [C] 回调函数
- C 回调函数
- C回调函数
- [C++]回调函数
- 回调函数实现
- 【C/C++】用回调函数实现计算器
- c/c++:回调函数
- C /C ++ 回调函数
- Objective-C利用协议实现回调函数(类似java的回调函数)
- Objective-C利用协议实现回调函数(类似java的回调函数)
- YetAnotherForum备忘录2
- SQL Server 索引基础知识(4)----主键与聚集索引
- jquery下拉菜单
- Java设计模式-----Bridge桥接模式
- [转载]java中用URLConnection 类post方式提交表单
- C++实现回调函数 funtor
- MOSS项目开发步骤
- AlwaysVisibleControl Demonstration
- 网站发布问题
- 应用系统性能优化过程
- 播放抓取的H263 RTP视频
- java初学者应该懂的
- ASP.NET两个常见的异常-不能创建Mutex、NETWORK SERVICE没有Temporary ASP.NET Files写访问权限
- 简易masterpage of moss