向下转换指向成员函数的指针.这是合法用法吗?

Downcasting pointer to member function. Is this legal usage?

本文关键字:用法 指针 转换 成员 函数      更新时间:2023-10-16

我将指向成员函数的指针列表存储在数组中。 我想索引到数组中并执行相应的函数。 将有许多数组列出来自不同类的函数(全部派生自 Base(,因此在编译时不知道该类。

我有这个方案在工作,但我对不得不在一个地方使用空指针并不完全满意,但我似乎无法避免它。

根据 C++11 标准,我在 Base 和派生成员函数指针之间的转换是否合法(它正在使用 g++(。我将不胜感激语言律师的建议!

下面是我的代码的精简版,但可运行。

#include <iostream>
using std::cout;
//*************************************
class Base {
public:
  typedef int (Base::*BaseThunk)();
  virtual int execute(BaseThunk x) {return 0;}
};
//*************************************
class Derived : public Base {
public:
  typedef int (Derived::*DerivedThunk)();
  int execute(BaseThunk step) {
    return (this->*step)(); //Is this OK ? step is really a DerivedThunk.
  }
  int f1() { cout<<"1n";return 1;}
  int f2() { cout<<"2n";return 2;}
  int f3() { cout<<"3n";return 3;}
  static DerivedThunk steps[];
};
//Here is an array of pointers to member functions of the Derived class.
Derived::DerivedThunk Derived::steps[] = {&Derived::f1, &Derived::f2, &Derived::f3};
//*************************************
class Intermediate : public Base {
public:
  void f(void *x) { //I am worried about using void pointer here !
    BaseThunk *seq = reinterpret_cast<BaseThunk *>(x);
    Derived d;
    d.execute(seq[2]);
  }
};
//*************************************
int main() {
  Intermediate b;
  b.f(&Derived::steps);
}

你对void*的担忧是有根据的:这是未定义的行为,因为(在Intermediate::f中(你正在对与数组类型不匹配的指针执行指针算术并通读。

好消息是有一个简单的解决方法:由于数组的目的是在给定Base&BaseThunk的情况下调用派生类函数,因此您可以存储该类型:

Base::BaseThunk Derived::steps[]=
  {static_cast<BaseThunk>(&Derived::f1),
   …};

static_cast有些冗长,但只要您将生成的 BaseThunk 对象类型为 或派生自 Derived 的对象一起使用,就完全合法。 您甚至不必先获得Derived*

int Base::execute(BaseThunk x)  // no need to be virtual
{return (this->*x)();}