c++ - 将新元素插入函数指针映射 "inline"?

标签 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;
}

我想知道是否可以“内联”定义 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/

相关文章:

c++ - 现代硬件上的浮点与整数计算

c++ - 使用 C++11 Range for 循环更改字符串中的字符

javascript - 无法在 JavaScript 中的可变长度参数数组上运行函数

c - 在 C 中将指针变量作为指向不同类型的指针进行访问

c++ - 重载、const 参数、const_cast、const_cast<string &>

function - 在管理分区的函数中删除某些表

c++ - 如何用语法表示动力学方程

c - 如何连接指针数组?

c - 这个C代码段有什么问题?当我不分配 t 它工作正常

c++ - 将参数传递给函数