指向派生 class 的成员函数的指针,但不是派生(虚)函数

Pointer to member function of derived class, but not derived(virtual) function

我有一个特别的问题要解决,我不确定是否可行,因为我找不到任何信息或正在解决的示例。 基本上,我有:

class ParentObject {};

class DerivedObject : public ParentObject
{
    void myFunction(){}
};

class OtherDerivedObject : public ParentObject
{
   void myOtherFunction(){}
};

并想要一个指向 ParentObject::* 的函数指针,并让它能够从任一派生的 class 获取函数。 我想这样做的原因,我还有另一个 class

class functionRegistry
{
  std::map<string, *functionPoint> functionMap;
}

并且每个对象(理想情况下在 ParentObject 中,但如果需要可以在派生对象中单独执行)都有一个 functionRegistry 实例,我需要 functionPoint 能够指向 DerivedObject 或 OtherDerivedObject 类型的对象中的函数。

提前致谢

您只需要 static_cast 即可使用正确的类型填充地图。

using pfunc_type = void (ParentObject::*)() ;
pfunc_type pfunc1 = static_cast<pfunc_type>(&DerivedObject::myFunction);

因为这是标准允许的:

[expr.static.cast/12] - §5.2.9¶12

A prvalue of type “pointer to member of D of type cv1 T” can be converted to a prvalue of type “pointer to member of B of type cv2 T”, where B is a base class (Clause [class.derived]) of D, if cv2 is the same cv-qualification as, or greater cv-qualification than, cv1.72 If no valid standard conversion from “pointer to member of B of type T” to “pointer to member of D of type T” exists ([conv.mem]), the program is ill-formed. The null member pointer value ([conv.mem]) is converted to the null member pointer value of the destination type. If class B contains the original member, or is a base or derived class of the class containing the original member, the resulting pointer to member points to the original member. Otherwise, the behavior is undefined. [ Note: although class B need not contain the original member, the dynamic type of the object with which indirection through the pointer to member is performed must contain the original member; see [expr.mptr.oper]. — end note ]

虽然这是允许的,但您必须非常小心,确保将指向成员的指针应用到具有正确动态类型的对象上。