c++ - 如何使用 Visual Studio 2008 将字符串映射到函数?

标签 c++ visual-studio visual-studio-2008 c++98

此问题引用了以下问题: Using a STL map of function pointers

在 C++11 中,我使用映射来存储 <string, function>配对可以更有效地执行代码,而不是使用 if...else if...else if如引用链接所述。

代码封装在成员函数中,其中 this引用类,允许访问成员变量。

using f = std::function<void()>;
static const std::map<std::string, f> doSumthin{
  {"case 1", [this]() {
    // execute code in case 1
  }},
  {"case 2", [this]() {
   // execute code in case 2
  }},
  …
};

auto it = doSumthin.find(someString);

if (it != doSumthin.end())
{
    it->second();
}

但是,我需要使代码库在 VS 2008 中工作。我不确定实现复制上述代码以在 VS 2008 中工作而不恢复到效率较低的最佳方式是什么 if...else if .

我可以获得有关此问题的一些指导吗?

最佳答案

#include <map>
#include <string>

typedef void (*func_ptr_type)();

void func_case_1() {}
void func_case_2() {}

static std::map<std::string, func_ptr_type> doSumthin;

void initMap()
{
    doSumthin["case 1"] = func_case_1;
    doSumthin["case 2"] = func_case_2;
}

int main()
{
    initMap();

    std::map<std::string, func_ptr_type>::iterator it = doSumthin.find("case 1");
    if (it != doSumthin.end())
    {
        it->second();
    }
    return 0;
}

关于c++ - 如何使用 Visual Studio 2008 将字符串映射到函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59658175/

相关文章:

c++ - 为什么此 C++ 代码会导致运行时错误?

c++ - 关于使用#pragma region 在 Visual Studio 中折叠代码块

visual-studio-2008 - VC++ 2008/2010 能否在同一代码上轻松使用?

visual-studio-2008 - VS2008 或 ReSharper 删除行的快捷方式

c++ - Boost::random::discrete_distribution 构建后如何改变权重

c++ - 封装和指向对象的指针

c++ - openGL 奇怪的错误?

visual-studio - 乌龟SubWCRev.exe生成前事件

c# - 如何将 native 库复制到 Visual Studio 2010 中的单元测试暂存目录

c++ - 在不阻塞资源的情况下有效地等待标志状态更改?