C++;底漆5。ed.不允许用lambda闭包代替函数指针? < C++入门>第14章。功能对象: // ordinary function int add(int i, int j) { return i + j; } // lambda, which generates an unnamed function-object class auto mod = [](int i, int j) { return i % j; }; // function-object class struct div { int operator()(int denominator, int divisor){ return denominator / divisor; } }; // maps an operator to a pointer to a function taking two ints and returning an int map<string, int(*)(int,int)> binops; // ok: add is a pointer to function of the appropriate type binops.insert({"+", add}); // {"+", add} is a pair § 11.2.3 (p. 426)

C++;底漆5。ed.不允许用lambda闭包代替函数指针? < C++入门>第14章。功能对象: // ordinary function int add(int i, int j) { return i + j; } // lambda, which generates an unnamed function-object class auto mod = [](int i, int j) { return i % j; }; // function-object class struct div { int operator()(int denominator, int divisor){ return denominator / divisor; } }; // maps an operator to a pointer to a function taking two ints and returning an int map<string, int(*)(int,int)> binops; // ok: add is a pointer to function of the appropriate type binops.insert({"+", add}); // {"+", add} is a pair § 11.2.3 (p. 426),c++,stdmap,function-object,lambda,C++,Stdmap,Function Object,Lambda,问题是mod是一个lambda,每个lambda都有自己的类类型。那个 类型与存储在binops中的值的类型不匹配 但如果我用这个: bin.insert( {"+", [](int x, int y){return x + y;} }); // works fine for me on GCC 是否属于C++ 20 C++之前的标准,它防止使用lambda ExPR代替函数指针?< /p>。是的,似乎是用gcc-std=c++11编译的。请发布包含所有相关#include和main的

问题是mod是一个lambda,每个lambda都有自己的类类型。那个 类型与存储在
binops
中的值的类型不匹配

但如果我用这个:

    bin.insert( {"+", [](int x, int y){return x + y;} }); // works fine for me on GCC

是否属于C++ 20 C++之前的标准,它防止使用lambda ExPR代替函数指针?< /p>。是的,似乎是用

gcc-std=c++11
编译的。请发布包含所有相关
#include
main
的完整文件。这很奇怪,GCC 9.3。您也可以使用std::function代替函数指针,这实际上是推荐的方法。@Maestro即使根据C++11标准[expr.prim.lambda/6],转换也是有效的,所以这本书在这里似乎是错的。@Maestro顺便说一句,在第六版中,这个例子已经不存在了。
    bin.insert( {"+", [](int x, int y){return x + y;} }); // works fine for me on GCC