开发者

calling methods in cpp like @selector(someMethod:) in Objective-C

开发者 https://www.devze.com 2023-01-08 17:50 出处:网络
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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号