C++实现回调函数 funtor
2008-06-05 16:48
555 查看
在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);
}
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++ 虚拟函数vs 回调函数 像有虚拟方法表一样有一个虚拟变量表就可以实现类级回调函数了
- C++中的Thunk技术 / 非静态类成员函数作为回调函数 的实现方法
- C++ 回调函数 实现 的测试代码
- Unity 之 C# 利用回调函数实现C++匿名函数
- c++中的回调函数的实现
- C++ 实现把非静态成员函数作为回调函数(非static)
- 不同类之间实现C++回调函数
- Unity 之 C# 利用回调函数实现C++匿名函数
- c# 调用c++带有回调函数方法的实现
- C++ 实现把非静态成员函数作为回调函数(非static)
- C++ 实现把非静态成员函数作为回调函数(非static)(转 待研究)
- 回调函数的C++ 封装(非静态成员函数的回调函数实现方法)
- C++的回调函数的简单实现
- 使用回调函数实现类型c++的泛型算法
- c# 调用c++带有回调函数方法的实现
- 回调函数C++ 实现 第二版
- C#中用委托实现C++的回调函数
- C#中用委托实现C++的回调函数
- ROS回调函数的类方法实现,both in Python 和 C++
- C++回调函数实现例子