В праймере 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)
Однако мы не можем хранить мод или div в binops:
binops.insert({"%", mod}); // error: mod is not a pointer to function
Проблема в том, что мод лямбда, и каждая лямбда имеет свой тип класса. Этот тип не соответствует типу значений, хранящихся в binops
.
Но если я использую это:
bin.insert( {"+", [](int x, int y){return x + y;} }); // works fine for me on GCC
Принадлежит ли он стандарту C ++ до c ++ 20, что запрещает использование лямбда-выражение вместо указателя на функцию?