1

我正在为我的应用程序编写一个简单的键绑定。到目前为止,我有 2 个数组(布尔 m_keys[256],字符串 m_functions)。

这是我的输入类(在 input.h 中)

class InputClass
{
public:

InputClass(){};
InputClass(const InputClass&){};
~InputClass(){};

void Initialize(){
    for(int i=0; i<256; i++)
    {
            m_keys[i] = false;
    functions[i] = "";
    }
}

bool AddFunc(unsigned int key, string func, bool overide)
{
      if((functions[key] == "") || (overide)){
      //overide is used to overide the current string (if there is one)
          functions[key] = func; 
          return true;
      } 
      return false;
    };

void KeyDown(unsigned int input){m_keys[input] = true;};

void KeyUp(unsigned int input){m_keys[input] = false;};

string IsKeyDown(unsigned int key){return m_keys[key] ? functions[key] : "";};

private:
    bool m_keys[256];
    string functions[256];
};

在我的 WinARM.cpp 中:

在我的初始化函数中

    INIT(m_Input, InputClass) //#define INIT(o,c) if(!(o = new c))return false;
    m_Input->Initialize();
    m_Input->AddFunc(VK_RETURN,"m_Graphics->ToggleWireFrame",true);

在我的帧函数中(运行每一帧;)

short SystemClass::Frame()
{
string func;
func = m_Input->IsKeyDown(VK_RETURN); //checks to see if the enter key is down
if(func !="") (func as function)(); // <-- this is the code i need help with
if(m_Input->IsKeyDown(VK_F2)!="")m_Graphics->ToggleWireFrame();
if(!m_Graphics->Frame()) return -1;
return 1;
}
4

1 回答 1

1

如果我理解正确,您正在尝试从字符串中获取可调用函数。C++ 缺乏反射,所以这样做确实不可行。您可以使用一些替代方案。

我的建议是让你的InputClass::functions数组包含函数指针,而不是字符串。然后,您可以将函数地址AddFunc而不是字符串传递给并相应地设置给定的数组成员。这对于非成员函数来说效果很好。如果您希望能够调用类实例的成员函数,我将创建InputClass::functions一个 s 数组并将由intostd::function返回的函子传递。std::bindAddFunc

于 2013-02-04T19:16:12.937 回答