calling methods in cpp like @selector(someMethod:) in Objective-C
In Objective-C y开发者_开发问答ou can pass a method A as a parameter of other method B. and call method A from inside method B very easily like this:
-(void) setTarget:(id)object action:(SEL)selectorA
{
if[object respondsToSelector:selectorA]{
[object performSelector:selectorA withObject:nil afterDelay:0.0];
}
}
Is there any functionally like this in C++ ?
C++ and Objective-C are quite different in that regard.
Objective-C uses messaging to implement object method calling, which means that a method is resolved at run-time, allowing reflectivity and delegation.
C++ uses static typing, and V-tables to implement function calling in classes, meaning that functions are represented as pointers. It is not possible to dynamically determine whether a class implements a given method, because there are no method names in memory.
On the other hand, you can use RTTI to determine whether a given object belongs to a certain type.
void callFunc(generic_object * obj) {
specific_object * spec_obj = dynamic_cast<specific_object*>(obj);
if (spec_obj != NULL) {
spec_obj->method();
}
}
Edit:
As per nacho4d's demand, here is an example of dynamic invocation :
typedef void (specific_object::*ptr_to_func)();
void callFunc(generic_object * obj, ptr_to_func f) {
specific_object * spec_obj = dynamic_cast<specific_object*>(obj);
if (spec_obj != NULL) {
((*spec_obj).*f)();
}
}
Yes there is, and they are called "Function Pointers", you will get lots of results googling around,
http://www.newty.de/fpt/index.html
http://www.cprogramming.com/tutorial/function-pointers.html
精彩评论