1

From my understanding, the + operator before a lambda expression resolves it to a function pointer overload. (Post)

However I do not understand quite understand why it does not work with generic lambdas. For example:

auto foo = +[](int a) { std::cout << "foo " << a << std::endl; };  // Valid

auto bar = +[](auto a) { std::cout << "bar " << a << std::endl; }; // Fails 

// compiler error: 
// no match for ‘operator+’ (operand type is ‘main()::<lambda(auto:1)>’)

What is the intuition behind this?

Live example

JeJo
  • 30,635
  • 6
  • 49
  • 88
Ammar Husain
  • 1,789
  • 2
  • 12
  • 26
  • 3
    You can only take a pointer to a function, but the generic lambda is essentially a template. You can however take a pointer to a specific instantiation of that template by casting, e.g. `auto bar = static_cast([](auto a) { std::cout << "bar " << a << std::endl; });` – Henri Menke Nov 08 '19 at 05:28
  • @HenriMenke - IMHO, you should expand your comment in an answer. – max66 Nov 08 '19 at 11:09

1 Answers1

0

So, the problem is in (auto a). How it will be look if you has no lamdas?

Then you should write a method

void FuncFirst(int a) { std::cout << "foo " << a << std::endl; }

and then use

auto foo = $FuncFirst;

So, second example seems strange:

void FuncSecond(auto a) { std::cout << "bar " << a << std::endl; } <-- So, how parameter can be "auto"? 

"auto" should resolved during compilation. What will be if you send it to some another methods and call it with different tupes of arguments? It too much uncertainty. If you want to create method that can accept different parameters than you can use themplates. (Or may be you can use int ? =) )

TemaTre
  • 1,422
  • 2
  • 12
  • 20