将新元素推送到函数指针的映射中"内联"?

时间:2017-03-17 01:11:20

标签: c++ function pointers function-pointers

我正在创建一个函数指针映射,如下面的最小工作示例所示:

#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;
}

我想知道是否可以定义地图的新元素(即函数)&#34; inline&#34;,即在代码中,而不必先在别处创建单独的函数在代码中(本例中为f1)。

编辑:解决方案最好是C ++ 98。

1 个答案:

答案 0 :(得分:4)

是的,无捕获的lambda表达式可以转换为函数指针:

myMap[3] = [](Bar) { return false; };
myMap[7] = [](Bar b) -> bool { b.clear(); return b.size(); };