如何在C++中找到变量派生最多的子类?

How to find the most derived subclass of a variable in C++?

本文关键字:派生 子类 变量 C++      更新时间:2023-10-16

IDK 如果问题有帮助,但在C++可以执行以下操作:

PinAbstract* pin1 = new ValuedPin<int>();
ValuedPin<int>* pin2 = new ValuedPin<int>();
std::cout << (get_most_derived_subclass(pin1) == get_most_derived_subclass(pin2)) << std::endl;
//OUTPUT should be:
1 <- Since both are at most ValuedPin<int>*'s, even if pin1 is declared as PinAbstract.

其中 PinAbstract 是 ValuedPin 的超类。typeid不适用于指针和值,因为对于 pin1,它返回 PinAbstract。

简短的回答是否定的,你问的是不可能的,因为C++没有比get_most_derived_subclass()更好的了。

但是,对于多态类型(具有virtual方法的类型(,可以使用dynamic_cast来确定给定对象是否实现了给定类型,例如:

PinAbstract* pin1 = ...;
std::cout << (dynamic_cast<ValuedPin<int>*>(pin1) != NULL) << std::endl;