view plaincopy to clipboardprint?
template < class Class, typename ReturnType, typename Parameter >
class SingularCallBack
{
public:
typedef ReturnType (Class::*Method)(Parameter);
SingularCallBack(Class* _class_instance, Method _method)
{
//取得对象实例地址,及调用方法地址
class_instance = _class_instance;
method = _method;
};
ReturnType operator()(Parameter parameter)
{
// 调用对象方法
return (class_instance->*method)(parameter);
};
ReturnType execute(Parameter parameter)
{
// 调用对象方法
return operator()(parameter);
};
private:
Class* class_instance;
Method method;
};
template < class Class, typename ReturnType, typename Parameter >
class SingularCallBack
{
public:
typedef ReturnType (Class::*Method)(Parameter);
SingularCallBack(Class* _class_instance, Method _method)
{
//取得对象实例地址,及调用方法地址
class_instance = _class_instance;
method = _method;
};
ReturnType operator()(Parameter parameter)
{
// 调用对象方法
return (class_instance->*method)(parameter);
};
ReturnType execute(Parameter parameter)
{
// 调用对象方法
return operator()(parameter);
};
private:
Class* class_instance;
Method method;
};
示例:
以下是两个类实现。
view plaincopy to clipboardprint?
class A
{
public:
void output()
{
std::cout << "I am class A :D" << std::endl;
};
};
class B
{
public:
bool methodB(A a)
{
a.output();
return true;
}
};
class A
{
public:
void output()
{
std::cout << "I am class A :D" << std::endl;
};
};
class B
{
public:
bool methodB(A a)
{
a.output();
return true;
}
};
view plaincopy to clipboardprint?
A a;
B b;
SingularCallBack< B,bool,A >* cb;
cb = new SingularCallBack< B,bool,A >(&b,&B::methodB);
if((*cb)(a))
{
std::cout << "CallBack Fired Successfully!" << std::endl;
}
else
{
std::cout << "CallBack Fired Unsuccessfully!" << std::endl;
}
A a;
B b;
SingularCallBack< B,bool,A >* cb;
cb = new SingularCallBack< B,bool,A >(&b,&B::methodB);
if((*cb)(a))
{
std::cout << "CallBack Fired Successfully!" << std::endl;
}
else
{
std::cout << "CallBack Fired Unsuccessfully!" << std::endl;
}
view plaincopy to clipboardprint?
A a;
B b;
SingularCallBack< B,bool,A >* cb;
cb = new SingularCallBack< B,bool,A >(&b,&B::methodB);
if(cb->execute(a))
{
std::cout << "CallBack Fired Successfully!" << std::endl;
}
else
{
std::cout << "CallBack Fired Unsuccessfully!" << std::endl;
}
A a;
B b;
SingularCallBack< B,bool,A >* cb;
cb = new SingularCallBack< B,bool,A >(&b,&B::methodB);
if(cb->execute(a))
{
std::cout << "CallBack Fired Successfully!" << std::endl;
}
else
{
std::cout << "CallBack Fired Unsuccessfully!" << std::endl;
}
view plaincopy to clipboardprint?
A a;
B b;
SingularCallBack< B,bool,A >cb(&b,&B::methodB);
if(cb(a))
{
std::cout << "CallBack Fired Successfully!" << std::endl;
}
else
{
std::cout << "CallBack Fired Unsuccessfully!" << std::endl;
}
A a;
B b;
SingularCallBack< B,bool,A >cb(&b,&B::methodB);
if(cb(a))
{
std::cout << "CallBack Fired Successfully!" << std::endl;
}
else
{
std::cout << "CallBack Fired Unsuccessfully!" << std::endl;
}
view plaincopy to clipboardprint?