定义未指定名称空间的函数指针

Defining a function pointer of an unspecified namespace

本文关键字:函数 指针 空间 定名称 定义      更新时间:2023-10-16

我正在为一款与朋友合作的游戏制作一个简单的开发者主机。我正在将函数绑定到控制台,所以我有一个std::map包含一个字符串来保存我们将在控制台调用它的名称,以及我自己定义的MFP类型,这是一个函数指针,返回sf:: string(我们使用SFML, sf是SFML名称空间),并接受sf:: string作为参数。所有控制台函数都接受一个sf::String参数,并返回一个sf::String参数。

下面是有问题的代码(不是全部代码):

#include <SFML/System/String.hpp>
using namespace sf;
#include <map>
#include <string>
using namespace std;
class CConsole
{
public:
    typedef sf::String (*MFP)(sf::String value);    //function pointer type
    void bindFunction(string name, MFP func);    //binds a function
    void unbindFunction(string name);    //unbinds desired function
private:
    map <string, MFP> functions;
}

现在这一切都很好,只要我们试图绑定到控制台的函数是全局命名空间。但这行不通。不断地为我们想要绑定到控制台的每个嵌套函数创建全局包装器函数,这将是效率太低了。

是否有可能使'MFP'接受所有名称空间的函数指针?例如,让下面的代码完美地工作?

#include "console.h"    //code shown above
//Let's also pretend CConsole has an sf::String(sf::String value) method called consoleFunc that returns "Hello from the CConsole namespace!"
sf::String globalFunc(sf::String value)
{
     return "Hello from the global namespace!";
}
int main()
{
    CConsole console;
    console->bindFunction("global", globalFunc);
    console->bindFunction("CConsole", CConsole::consoleFunc);
    return 0;
}

在您的示例中,您可以在任何非成员函数或任何类的静态成员函数上调用bindFunction。不能使用非静态成员bindFunction,因为它们具有不同的类型。