简体   繁体   English

有没有办法在运行时确定对象是否可以在C ++中执行方法?

[英]Is there a way to determine at runtime if an object can do a method in C++?

In Perl, there is a UNIVERSAL::can method you can call on any class or object to determine if it's able to do something: 在Perl中,有一个UNIVERSAL :: can方法可以调用任何类或对象来确定它是否能够执行某些操作:

sub FooBar::foo {}
print "Yup!\n" if FooBar->can('foo'); #prints "Yup!"

Say I have a base class pointer in C++ that can be any of a number of different derived classes, is there an easy way to accomplish something similar to this? 假设我在C ++中有一个基类指针,它可以是许多不同的派生类中的任何一个,是否有一种简单的方法来完成与此类似的操作? I don't want to have to touch anything in the other derived classes, I can only change the area in the base class that calls the function, and the one derived class that supports it. 我不想触及其他派生类中的任何内容,我只能更改调用该函数的基类中的区域,以及支持它的派生类。

EDIT: Wait, this is obvious now (nevermind the question), I could just implement it in the base that returns a number representing UNIMPLEMENTED, then check that the return is not this when you call it. 编辑:等等,现在这是显而易见的(永远不要回答问题),我可以在基数中实现它,返回一个代表UNIMPLEMENTED的数字,然后在调用时检查返回不是这个。 I'm not sure why I was thinking of things in such a complicated manner. 我不确定为什么我会以如此复杂的方式思考问题。

I was also thinking I would derive my class from another one that implemented foo then see if a dynamic cast to this class worked or not. 我也在想我会从另一个实现foo类派生出我的类,然后看看这个类的动态转换是否有效。

如果你有一个指向基类的指针或引用,你可以使用dynamic_cast来查看它是哪个派生类(以及它支持的派生类的方法)。

如果可以向基类添加方法,则可以添加virtual bool can_foo() {return false;}并在具有foo的子类中覆盖它以返回true。

C++ does not have built in run-time reflection. C ++没有内置的运行时反射。 You are perfectly free to build your own reflection implementation into your class hierarchy. 您可以完全自由地在类层次结构中构建自己的反射实现。 This usually involves a static map that gets populated with a list of names and functions. 这通常涉及一个静态地图,其中填充了一系列名称和功能。 You have to manually register each function you want available, and have consistency as to the calling convention and function signature. 您必须手动注册所需的每个函数,并且具有调用约定和函数签名的一致性。

I believe the most-correct way would be to use the typeid<> operator and get a reference to the type_info object, and then you could compare that (== operator) to the desired type_info for the data types you wish to care about. 我认为最正确的方法是使用typeid <>运算符并获取对type_info对象的引用,然后您可以将该(==运算符)与您希望关注的数据类型的所需type_info进行比较。

This doesn't give you method-level inspection, and does require that you've built with RTTI enabled (I believe that using typeid<> on an object that was built without RTTI results with "undefined" behavior), but there you are. 这不会给你方法级别的检查,并且确实要求你已经启用了RTTI(我相信在没有RTTI的情况下使用“未定义”行为构建的对象上使用typeid <>),但是你有。

MSDN has an online reference to get you started : http://msdn.microsoft.com/en-us/library/b2ay8610%28VS.80%29.aspx MSDN有一个在线参考,可以帮助您入门: http//msdn.microsoft.com/en-us/library/b2ay8610%28VS.80%29.aspx

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

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