8
auto f1 = []<typename T>(T) { return T{}; };
auto f2 = []<typename T>()  { return T{}; };

int main()
{
    f1(1);     // ok
    f2<int>(); // err: expected primary-expression before 'int'
}

Why does C++20 not allow to call a generic lambda with an explicit type?

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
xmllmx
  • 39,765
  • 26
  • 162
  • 323
  • Do you really mean **why** (which the accepted answer doesn’t address), or does this answer your question? [limits and uses of C++20 template lambas](https://stackoverflow.com/questions/59592122/limits-and-uses-of-c20-template-lambas) – Davis Herring Apr 24 '21 at 15:06

1 Answers1

9

The correct syntax to invoke overloaded template operator () function supplying template parameters is

auto f1 = []<typename T>(T) { return T{}; };
auto f2 = []<typename T>()  { return T{}; };

int main()
{
    f1(1);     // ok
    f2.operator ()<int>(); // Ok
}

https://godbolt.org/z/YzY7njPGh

user7860670
  • 35,849
  • 4
  • 58
  • 84
  • 2
    Just a nitpick, but in this case the `operator()` is not overloaded. It's just a template. Solution remains the same. – super Apr 24 '21 at 07:49
  • 2
    @super It is an overloaded operator, see https://en.cppreference.com/w/cpp/language/operators – user7860670 Apr 24 '21 at 07:51
  • 1
    Not sure what part of that link is relevant here. The unnamed struct generated by the lambda syntax will only have one `operator()`, so it's not overloaded. What am I missing? – super Apr 24 '21 at 07:54
  • 3
    @super It is called an overloaded operator in contrast to built-in operators, not in the sense of overloaded function. – user7860670 Apr 24 '21 at 07:58