c++ - 指向派生类成员函数的指针,但不是派生(虚拟)函数

标签 c++ inheritance function-pointers pointer-to-member

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

class ParentObject {};

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

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

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

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

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

提前致谢

最佳答案

您所需要的只是一个static_cast,以使用正确的类型填充 map 。

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 ]

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

关于c++ - 指向派生类成员函数的指针,但不是派生(虚拟)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41347826/

相关文章:

c++ - 对不同的结果使用具有相同值的枚举? C++

java - “every class in java extends the MetaClass Object” 是否意味着每个子类都会导致 Diamond 问题

c++ - 如何创建可以使用字符串参数自动初始化其他类的类

c++ - 传入并存储指向对象的函数指针

c - C 中这些函数指针之间的转换安全吗?

delphi - 如何将方法指针作为窗口消息参数发送?

c++ - GCC/Linux : adding a static library to a . 所以?

c++ - 用对角线表示法写一个名字

c++ - QT UI 测试的最佳方法

javascript - 如何最好地从原生 JavaScript 对象继承? (尤其是字符串)