首页 > 解决方案 > 在类中声明函数数组

问题描述

我在一个类中有一批函数:

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 语句更快,但我想检查一下。

谢谢。

标签: c++arraysfunction

解决方案


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.


推荐阅读