思路是借助类的静态成员函数
方式一:
class A{
public:
A(int a){
m_a = a;
}
void print(){
cout << "m_a = " << m_a << endl;
}
void setCur(){
s_curA = this;
}
static void callback(){
s_curA->print();
}
private:
static A* s_curA;
int m_a;
};
A* A::s_curA = nullptr;
typedef void (*FUN_S)();
void Handle(FUN_S call){
call();
}
int main( )
{
A a(10), b(20);
a.setCur();
Handle(A::callback);
b.setCur();
Handle(A::callback);
return 0;
}
方式二:
class A{
public:
A(int a){
m_a = a;
}
void print(){
cout << "m_a = " << m_a << endl;
}
static void callback(void *a){
((A*)a)->print();
}
private:
int m_a;
};
typedef void (*FUN)(void *);
void Handle(void *a, FUN call){
call(a);
}
int main( )
{
A a(10), b(20);
Handle(&a, A::callback);
Handle(&b, A::callback);
return 0;
}
输出:
Start
m_a = 10
m_a = 20
0
Finish
还可以进一步封装:
typedef void (*FUN_S)();
void Handle(FUN_S call){
cout << "Handle(FUN_S) begin..." << endl;
call();
cout << "Handle(FUN_S) end..." << endl;
}
typedef void (*FUN)(void *);
void Handle(void *a, FUN call){
cout << "Handle(void *, FUN) begin..." << endl;
call(a);
cout << "Handle(void *, FUN) end..." << endl;
}
class A{
public:
A(int a){
m_a = a;
}
void print(){
cout << "m_a = " << m_a << endl;
}
void setCur(){
s_curA = this;
}
void startup(){
setCur();
Handle(A::callback);
}
void startup(int){
Handle(this, A::callback);
}
static void callback(){
s_curA->print();
}
static void callback(void *a){
((A*)a)->print();
}
private:
static A* s_curA;
int m_a;
};
A* A::s_curA = nullptr;
int main( )
{
A a(10), b(20);
a.startup();
b.startup();
cout << "======================================" << endl;
a.startup(1);
b.startup(1);
return 0;
}
输出:
Start
Handle(FUN_S) begin...
m_a = 10
Handle(FUN_S) end...
Handle(FUN_S) begin...
m_a = 20
Handle(FUN_S) end...
======================================
Handle(void *, FUN) begin...
m_a = 10
Handle(void *, FUN) end...
Handle(void *, FUN) begin...
m_a = 20
Handle(void *, FUN) end...
0
Finish