2

In C++ primer chapter 14. Function objects:

// 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)

However, we can’t store mod or div in binops:

binops.insert({"%", mod}); // error: mod is not a pointer to function

The problem is that mod is a lambda, and each lambda has its own class type. That type does not match the type of the values stored in binops.

But if I use this:

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

Does it belong to C++ standard prior to c++ 20 that prevents using a lambda-expr in place of a pointer to function?

Maestro
  • 2,512
  • 9
  • 24

0 Answers0