c++ - 在类中声明函数数组
问题描述
我在一个类中有一批函数:
class Edges // Edges of a Rubik's cube
{
// Stuff
protected:
// Edges movements
void e_U();
void e_D();
void e_F();
void e_B();
void e_R();
void e_L();
// More stuff
};
一个新类继承了这个函数:
class Cube: public Edges // Rubik's cube class
{
public:
void U(int); // U slice edges movement relative to spin
// Stuff
}
所需函数的调用取决于一个数字,如下代码所示:
void Cube::U(int spin) // U slice movement for the given spin
{
switch (spin)
{
case 0: e_U(); return;
case 1: e_U(); return;
case 2: e_U(); return;
case 3: e_U(); return;
case 4: e_D(); return;
...
case 23: e_L(); return;
default: return;
}
}
我想提高性能,所以我把函数放在一个数组中:
class Cube: public Edges // Rubik's cube class
{
public:
void U(int); // U slice edges movement relative to spin
// Stuff
private:
const static void (*(USlice[24]))(); // U slice edges movement relative to spin
// More stuff
}
const void Cube::( (*(USlice[24]))() ) =
{
e_U, e_U, e_U, e_U,
e_D, e_D, e_D, e_D,
e_F, e_F, e_F, e_F,
e_B, e_B, e_B, e_B,
e_R, e_R, e_R, e_R,
e_L, e_L, e_L, e_L
};
所以 U 函数现在应该是这样的:
void Cube::U(int spin) // U slice movement for the given spin
{
USlice[spin]();
}
我的问题是我找不到在类中声明函数数组的正确方法。我已经尝试了我能想到的一切(删除“const”和“static”语句,公开所有内容,...)
数组应该是“static”和“const”,成员是 24 个没有参数的“void”函数。
实际上我不知道在数组中声明函数是否会比使用 switch 语句更快,但我想检查一下。
谢谢。
解决方案
Actually, for only performance, you don't need to use array of function pointers.
There is no speed difference.
Using function pointers, it tooks 1 MOV operation in asm(about 2 DWORD), while using switch tooks 1~2 CMP or TEST operations(about 2-6 WORD, because there are only 6 unique functions in 24sets).
The errors you mentioned is that, values of array are the function pointers to protected member function - not global function.
This means, you have to think about 1st function parameter is *this
which is invisible to c++ code.
推荐阅读
- scala - Kafka Streams:配置“AdminClientConfig”或“ConsumerConfig”而不覆盖两者的值
- python - 如何在我的分布式项目中运行网络服务器模块?
- h2o - 错误:H2o 自动编码器训练中的模型很大
- excel - 如何隐藏行中没有数据的行
- php - 修复预期的数组但得到了对象?
- python - 无法使用 bs4 从 BSE 网站上抓取特定信息
- c# - 服务器上的缩略图 - GDI+ 中出现一般错误
- python - 使用 Python mysql.connector 将包含表情符号的 unicode API 响应插入 Mysql
- postgresql - Postgres:使用 PGAdmin 将数据库从一台服务器复制到 AWS RDS 上的另一台服务器
- java - ArrayList 不会存储来自用户输入的实例