C++:如何传递通用函数名?

Tub*_*bbs 13 c++ function

我正在用c ++构建一个程序,用户可以设置一个在达到用户定义的条件时调用的函数.我对c ++只有一点经验.

我知道如何在python中执行此操作.您只需定义函数并将所述函数的名称放入结构中(我总是使用字典).当你去使用这个功能时,你会拨打一个类似于的电话:

methods = { "foo" : foo, "bar" : bar } 
choice = input("foo or bar? ")
methods[choice]()
Run Code Online (Sandbox Code Playgroud)

关于如何在c ++中解决这个问题而不必对所有内容进行硬编码的任何想法?

Jam*_*lis 22

您可以使用函数指针的映射:

void foo() { }
void bar() { }

typedef void (*FunctionPtr)();
typedef std::map<std::string, FunctionPtr> FunctionMap;

FunctionMap functions;
functions.insert(std::make_pair("foo", &foo));
functions.insert(std::make_pair("bar", &bar));

std::string method = get_method_however_you_want();

FunctionMap::const_iterator it(functions.find(method));
if (it != functions.end() && it->second)
    (it->second)();
Run Code Online (Sandbox Code Playgroud)

  • 为什么`insert()`和`&foo`而不是`functions ["foo"] = foo;`?它们本质上是等价的,但后者更具可读性.此外,只有在地图包含空条目时才需要测试`it-> second`,这似乎不太可能.并且`it-> second()`在没有额外括号的情况下工作得很好. (2认同)
  • @Jon:首先,`&foo`是恕我直言.我不喜欢从函数名到函数指针的隐式转换.关于`insert` vs`manitor []`的问题,请点击[this link](http://stackoverflow.com/questions/5692187/stl-map-insertion-efficiency-vs-insert/5692257#5692257).接下来,测试完全没问题,您永远不知道代码的用户可能会做什么. (2认同)

jal*_*alf 8

您的Python代码实际上直接转换为C++:

# Python:
# Create a dictionary mapping strings to functions
methods = { "foo" : foo, "bar" : bar } 
// C++:
// create a map, mapping strings to functions (function pointers, specifically)
std::map<std::string, void(*)()> methods; 
methods["foo"] = foo;
methods["bar"] = bar;

# Python
choice = input("foo or bar? ")
// C++:
std::string choice;
std::cout << "foo or bar? ";
std::cin >> choice;

# Python:
methods[choice]()
// C++
methods[choice]();
Run Code Online (Sandbox Code Playgroud)

Python的字典类似于C++的字典map.它们都是关联容器,将值从一种类型映射到另一种类型的值(在我们的例子中,字符串到函数).在C++中,函数不是一等公民,因此您不能在地图中存储函数,但可以存储指向函数的指针.因此,映射定义有点毛茸茸,因为我们必须指定值类型是"指向不带参数且返回void的函数的指针".

在旁注中,假设您的所有函数都具有相同的签名.我们不能存储返回void的函数和在同一映射中返回int的函数,而不需要额外的技巧.


lou*_*ear 6

你可以看一下函数指针:

http://www.newty.de/fpt/intro.html