将新元素“内联”到函数指针映射中?

问题描述 投票:0回答:1

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

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

我想知道是否可以“内联”定义地图的新元素(即函数),即就在代码中,而不必先在代码的其他地方创建一个单独的函数(

f1
在这个例如)。

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

c++ function pointers function-pointers
1个回答
4
投票

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

myMap[3] = [](Bar) { return false; };
myMap[7] = [](Bar b) -> bool { b.clear(); return b.size(); };
© www.soinside.com 2019 - 2024. All rights reserved.