将文本字符串与函数关联

时间:2014-04-14 17:54:45

标签: c++ string

这是我的解决方案,它需要测试运行来计算const值才能运行。这很尴尬,你有更优雅的解决方案吗?我在想我不会这样做,而是要做100次字符串比较。

//find these values before hand
char a[] = "SHET"; //1413826643
char b[] = "ANIM"; //1296649793
char c[] = "RGST"; //1414743890
int* get_word_value[] = { (int*)a, (int*)b, (int*)c };

//enum in header file makes it externally linked and compatible with switch statement
enum str_command{ SHET = 1413826643, ANIM = 1296649793, RGST = 1414743890 } ;
//cpp:
char* file = readTXT( "text.txt" );
int* command = (int*)file;
switch( command ) {
case SHET: SHETfunc( file ); break;
case ANIM: ANIMfunc( file ); break;
case RGST: RGSTfunc( file ); break;
}

2 个答案:

答案 0 :(得分:5)

为什么不

 std::map<std::string, std::function<here goes what the return types etc are>> dispatch;

Then

 dispatch["a string"](args);

您可以使用来自“

”的map_list_of初始化列表

答案 1 :(得分:1)

另一种流行的方法是使用查找表:

typedef void (*Function_Pointer)(/* input parameters*/);

struct Name_Function_Entry
{
  std::string  name;
  Function_Pointer function;
};

void Shet(void);
void Anim(void);
void Rgst(void);

const Name_Function_Entry function_table[] =
{
  {"SHET", Shet},
  {"ANIM", Anim},
  {"RGST", Rgst},
};
const unsigned int number_of_entries =
  sizeof(function_table) / sizeof(function_table[0]);

// ...
for (unsigned int i = 0; i < number_of_entries; ++i)
{
   if (name == function_table[i].name)
   {
      (function_table[i].function)();
      break;
   }
}