我正在创建一个函数指针映射,如下面的最小工作示例所示:
#include <iostream>
#include <map>
#include <vector>
using namespace std;
typedef std::vector<bool > Bar;
typedef bool (*Foo)(Bar b);
typedef std::map<int, Foo > MapOfFunctions;
inline bool f1 (Bar b) { return b[0] && b[1]; }
int main() {
MapOfFunctions myMap;
myMap[0] = f1; // works
//myMap[1] = // Define a function right here, "in line"?!
if (myMap[0](Bar (2,true) ))
cout << "it's true" << endl;
return 0;
}
我想知道是否可以“内联”定义 map 的新元素(即函数),即就在代码中,而不必首先在代码的其他地方创建一个单独的函数( f1
在这个例子中)。
编辑:解决方案最好是C++98。
最佳答案
是的,无捕获 lambda 表达式可以转换为函数指针:
myMap[3] = [](Bar) { return false; };
myMap[7] = [](Bar b) -> bool { b.clear(); return b.size(); };
关于c++ - 将新元素插入函数指针映射 "inline"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42847499/