简体   繁体   English

调用cpp中的方法,比如Objective-C中的@selector(someMethod :)

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

In Objective-C you can pass a method A as a parameter of other method B. and call method A from inside method B very easily like this: 在Objective-C中,您可以将方法A作为其他方法B的参数传递,并从方法B内部调用方法A,如下所示:

-(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 ++中有没有这样的功能?

C++ and Objective-C are quite different in that regard. 在这方面,C ++和Objective-C是完全不同的。

Objective-C uses messaging to implement object method calling, which means that a method is resolved at run-time, allowing reflectivity and delegation. Objective-C使用消息传递来实现对象方法调用,这意味着在运行时解析方法,允许反射和委托。

C++ uses static typing, and V-tables to implement function calling in classes, meaning that functions are represented as pointers. C ++使用静态类型和V表来实现类中的函数调用,这意味着函数表示为指针。 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. 另一方面,您可以使用RTTI来确定给定对象是否属于某种类型。

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 : 根据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)();
    }
}

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.newty.de/fpt/index.html

http://www.cprogramming.com/tutorial/function-pointers.html http://www.cprogramming.com/tutorial/function-pointers.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM