0
我需要在类层次结构中使用不同类型执行一些相等性检查。在伪代码:获取具有基类函数的派生类
#include <string>
#include <memory>
#include <iostream>
using namespace std;
class ComplexType {};
class Property {};
class IntegerProperty : public Property {
public:
int inner;
};
class StringProperty : public Property {
public:
string inner;
};
class ComplexTypeProperty : public Property {
ComplexType inner;
};
int main() {
shared_ptr<Property> p1 = getSomewhere(); //this is in fact a pointer on IntegerProperty
shared_ptr<Property> p2 = getSomewhere(); // this is in fact a pointer on StringProperty
shared_ptr<Property> p3 = getSomewhere(); // this is in fact a pointer on CompleyTypeProperty
ComplexType c;
cout << ((*p1) == 2);
cout << ((*p2) == "foo");
cout << ((*p3) == c);
}
它可以轻松提供派生类的一个operator==
,但检查之前,我不能投,因为p1
和p2
类型是在编译时明确。
我知道另一种方式是写在Property
基类operator==
功能,并抛出一些例外情况,如果该类型是错误的,但我想,那Property
级以后可以在不改变代码Property
子类,它会工作也是如此。
模板Property
也不是(直接)可能的,因为例如,在我的代码中必须存在vector<shared_ptr<Property>>
。
是否有一些(通用)的方式来实现main()以获得相等性检查,以便稍后子类化Property
而不更改类本身是可能的?
如果我已经理解了您要求的正确内容,则应该在网上搜索* double dispatch *。 – BoBTFish
@BoBTFish:如果我得到_double dispatch_权限,这可以与ComplexType一起使用,但不能与Integer,String ...一起使用,因为它们不共享公共超类。 – gerion
也许运营商==与std :: variant或任何?只是抛出想法... –