[英]C++20 lambdas with non type template parameters
I'm messing around with new C++20 lambdas, it seems I can declare a lambda taking a non type template param, but then I'm not able to call it.我在弄乱新的 C++20 lambda,似乎我可以声明一个 lambda 接受一个非类型模板参数,但是我无法调用它。
#include <iostream>
int main() {
// compiles fine
auto f = []<bool ok>() { return ok; };
// it even has an address??
std::cout << &f;
// f(); // error : no matching function for call to object of typ
// f<true>(); // error : invalid operands to binary expression
f.operator()<true>(); // compiles but somewhat... ugly
}
I looked at the relevant paper here but it doesn't seem to mention the calling syntax in such a case.我在这里查看了相关论文,但它似乎没有提到这种情况下的调用语法。
Is explicitly passing template arguments at the lambda call site forbidden?是否禁止在 lambda 呼叫站点明确传递模板 arguments? It would be a disappointing limitation, as I thought the intention was to make lambdas able to do as much as templates.这将是一个令人失望的限制,因为我认为这样做的目的是让 lambda 能够像模板一样做很多事情。
Is explicitly passing template arguments at the lambda call site forbidden?是否禁止在 lambda 呼叫站点明确传递模板 arguments?
No, but the issue is you're not specifying the template argument for the right entity.不,但问题是您没有为正确的实体指定模板参数。 Note that f
itself is not a template.请注意, f
本身不是模板。 It's an object of a non-templated type that contains a member operator()
that is templated.它是一个非模板类型的 object,它包含一个模板化的成员operator()
。
So when you do:所以当你这样做时:
f<true>(); // error
you are specifying the template argument for f
, but since f
is not a template, you get an error.您正在为f
指定模板参数,但由于f
不是模板,您会收到错误消息。
On the other hand, as you've observed, this call:另一方面,正如您所观察到的,这个调用:
f.operator()<true>(); // ok
is fine, because you are specifying the template argument for f
's operator()
which is indeed a template.很好,因为您正在为f
的operator()
指定模板参数,这确实是一个模板。
Also, this issue has nothing to do with non-type template parameters for lambdas, the same thing would happen if it were a type template parameter as well.此外,此问题与 lambda 的非类型模板参数无关,如果它也是类型模板参数,也会发生同样的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.