为什么C++20不允许使用显式类型调用泛型lambda?

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'
}

为什么 C++20 不允许使用显式类型调用泛型 lambda?

回答

调用提供模板参数的重载模板运算符 () 函数的正确语法是

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

  • @super It is called an overloaded operator in contrast to built-in operators, not in the sense of overloaded function.
  • Just a nitpick, but in this case the `operator()` is not overloaded. It's just a template. Solution remains the same.
  • @super It is an overloaded operator, see https://en.cppreference.com/w/cpp/language/operators

以上是为什么C++20不允许使用显式类型调用泛型lambda?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>