Calling methods in cpp, e.g. @selector (someMethod :) in Objective-C

In Objective-C, you can pass method A as a parameter to another method B. And the method of calling A from inside method B is very easy:

-(void) setTarget:(id)object action:(SEL)selectorA
{
    if[object respondsToSelector:selectorA]{
       [object performSelector:selectorA withObject:nil afterDelay:0.0];
    }
}

Is there functionally similar in C ++?

+3
source share
2 answers

C ++ and Objective-C are very different in this regard.

Objective-C uses messaging to implement an object method call, which means the method is allowed at run time, which allows reflection and delegation.

++ V- , , . , , .

, RTTI, , .

void callFunc(generic_object * obj) {
    specific_object * spec_obj = dynamic_cast<specific_object*>(obj);
    if (spec_obj != NULL) {
        spec_obj->method();
    }
}

Edit:

nacho4d, :

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)();
    }
}
+5

Source: https://habr.com/ru/post/1755688/


All Articles