如何在c ++中创建map <string,class :: method>并能够搜索并调用它?

use*_*872 15 c++ mapping function-pointers

我正在尝试用C++创建一个字符串和方法的映射,但我不知道该怎么做.我想做那样的事情(伪代码):

map<string, method> mapping =
{
  "sin", Math::sinFunc,
  "cos", Math::cosFunc,
  ...
};

...

string &function;
handler = mapping.find(function);
int result;

if (handler != NULL)
  result = (int) handler(20);
Run Code Online (Sandbox Code Playgroud)

说实话,我不知道在C++中是否可行.我想有一个字符串,方法的地图,并能够在我的映射中搜索功能.如果给定函数的字符串名称,那么我想用给定的param调用它.

Dum*_*001 19

好吧,我不是这里流行的Boost Lovers Club的成员,所以在这里 - 原始C++.

#include <map>
#include <string>

struct Math
{
    double sinFunc(double x) { return 0.33; };
    double cosFunc(double x) { return 0.66; };
};

typedef double (Math::*math_method_t)(double);
typedef std::map<std::string, math_method_t> math_func_map_t;

int main()
{

    math_func_map_t mapping;
    mapping["sin"] = &Math::sinFunc;
    mapping["cos"] = &Math::cosFunc;

    std::string function = std::string("sin");
    math_func_map_t::iterator x = mapping.find(function);
    int result = 0;

    if (x != mapping.end()) {
        Math m;
        result = (m.*(x->second))(20);
    }
}
Run Code Online (Sandbox Code Playgroud)

显然,如果我已经正确理解你想要一个方法指针,而不是一个函数/静态方法指针.


Jus*_*ini 6

由于函数指针,这确实可以在C++中实现.这是一个简单的例子:

  std::string foo() { return "Foo"; }
  std::string bar() { return "Bar"; }

  int main()
  {
      std::map<std::string, std::string (*)()> m;

      // Map the functions to the names
      m["foo"] = &foo;
      m["bar"] = &bar;

      // Display all of the mapped functions
      std::map<std::string, std::string (*)()>::const_iterator it = m.begin();
      std::map<std::string, std::string (*)()>::const_iterator end = m.end();

      while ( it != end ) {
          std::cout<< it->first <<"\t\""
              << (it->second)() <<"\"\n";
          ++it;
      }
  }
Run Code Online (Sandbox Code Playgroud)

在处理具有不同返回类型和参数的函数时,这会变得更加棘手.此外,如果您包含非静态成员函数,则应使用Boost.Function.