【问题标题】:How to assign a string to a function C++如何将字符串分配给函数 C++
【发布时间】:2014-03-23 17:51:25
【问题描述】:

所以使用一堆 if 语句,我想有人可以用更好的方法帮助我。

这就是我想要做的。 假设我有 3 个字符串,如果找到该字符串,我想为该字符串分配一个函数...

目前我正在做的一个基本示例:

if(findStr(string1)) {
    function1(perams);
}
else if (findStr(string2)) {
    function2(perams);
}
else if (findStr(string3)) {
    function3(perams);
}

我正在做一些类似的更大范围的事情,10 个不同的字符串,每个字符串对应于它自己的功能。

我对可能涉及我的字符串结构的选项持开放态度?

我只想做一个 if 语句,即使涉及循环。我不想调用“function1”、“function2”、“function3” 我希望它以某种方式与字符串相关联。

这可以干净地做吗?还是 if 语句是最干净的方法?

谢谢大家

【问题讨论】:

  • 使用std::map<std::string,FnPtrType> 怎么样,其中FnPtrType 类似于typedef void (*FnPtrType)(Params&)

标签: c++ string function if-statement


【解决方案1】:

您可以使用与函数指针关联的字符串映射,即:

如果是班级成员:

    typedef void (MyClass::*f)( peramsType);
    typedef map< std::string, f> MyMap;

用法

MyClass t;
f f_ptr = myMap["string1"];
( t.*f_ptr)( perams); // -> call function pointed by f_ptr through t object

如果是非班级成员:

    typedef void (*f)( peramsType);
    typedef map< std::string, f> MyMap;

用法:

f f_ptr = myMap["string1"];
( *f_ptr)( perams); // -> call non-class function pointed by f_ptr

好的做法是从 std::function 派生,所以你可以这样写:

#include <functional>

typedef std::function< void( peramsType)> f;
std::map < std::string, f> MyMap;

【讨论】:

  • 注意:使用 C++11 表示法将类型名称放在 outsideusing f = void (MyClass::*)(params);
【解决方案2】:

您可能想要使用对数组(字符串、函数指针),例如:

struct {
  string s;
  void (*f)(Params p);
} my_map[] = { { string1, function1}, {string2, function2} };

for (int i = 0; i < 2; i++) {
  if (findStr(my_map[i].s)) {
    my_map[i].f(perams);
    break;
  }
}

【讨论】:

  • 这里的所有答案都很棒,并提供了很多帮助。这个例子最接近我的想法。谢谢启发
【解决方案3】:

您可以将字符串映射到函数指针,检查字符串是否在映射中,然后调用它。像这样的:

typedef void(*Func)();

void foo1();
void foo2();
void foo3();

std::map<std::string, Func> m =
    { {"first", foo1}, {"second", foo2}, {"third", foo3} };

std::string str = "first";
auto it = m.find(str);
if (it != m.end()) (it->second)();

【讨论】:

    【解决方案4】:

    在 C++11 中你可以这样做:

    #include <functional>
    #include <map>
    #include <string>
    
    typedef std::function<void(PARAMS)> func_t;
    typedef std::map<std::string,func_t> map_t;
    

    其中 PARAMS 是您的函数参数列表。例如,std::function&lt;void(int,float)&gt; 表示一个函数,它接受两个参数,一个int 和一个float

    有关std::function 的更多信息,请参阅here

    【讨论】:

    • 我希望人们不要强迫std::function 处理函数指针的每一个问题。只有当您需要将异构可调用对象存储在同一个容器中时才需要它,否则会增加不必要的开销,恕我直言。
    • 恕我直言,使用 std::function 代码更容易阅读,而且开销(很可能)只在编译时支付 - 而不是在运行时支付。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 2012-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多