向下转换指向成员函数的指针.这是合法用法吗?
Downcasting pointer to member function. Is this legal usage?
我将指向成员函数的指针列表存储在数组中。 我想索引到数组中并执行相应的函数。 将有许多数组列出来自不同类的函数(全部派生自 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)();}
相关文章:
- 这个指针在c++中的用法
- 访问提升:shared_ptr 主范围外崩溃,断言失败:px != 0.指针的正确用法是什么?
- 使用指针复制构造函数用法
- 我不知道结构和指针的这种用法
- 向下转换指向成员函数的指针.这是合法用法吗?
- 引用和指向常量的指针的用法是什么
- 基于智能指针的 CRTP 习惯用法的编译问题
- 指向成员非类型模板参数的指针的实际用法
- 类指针用法
- 如何制作具有动态大小的数组?动态数组的一般用法(可能还有指针)
- 指针数组用法
- 智能指针中标量和数组的用法
- ->智能指针中的用法
- 广度优先搜索中的 C++ 迭代器和指针用法
- 在 C++ 函数指针上的用法
- 指针的这些用法有什么区别
- 类和对象中带有new的用法指针
- 带有智能指针的虚拟构造函数习惯用法
- 静态指针的c++用法
- 命名参数习惯用法,使用指向类私有方法的指针