本文介绍了带有非类型模板参数的 C++20 lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在处理新的 C++20 lambda,似乎我可以声明一个采用非类型模板参数的 lambda,但随后我无法调用它.

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.

#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.

是否禁止在 lambda 调用站点显式传递模板参数?这将是一个令人失望的限制,因为我认为目的是让 lambda 能够像模板一样做很多事情.

Is explicitly passing template arguments at the lambda call site forbidden? It would be a disappointing limitation, as I thought the intention was to make lambdas able to do as much as templates.

推荐答案

否,但问题是您没有为正确的实体指定模板参数.请注意,f 本身不是模板.它是一个非模板类型的对象,包含一个被模板化的成员 operator().

No, but the issue is you're not specifying the template argument for the right entity. Note that f itself is not a template. It's an object of a non-templated type that contains a member operator() that is templated.

所以当你这样做时:

f<true>(); // error

您正在为 f 指定模板参数,但由于 f 不是模板,您会收到错误消息.

you are specifying the template argument for f, but since f is not a template, you get an error.

另一方面,正如您所观察到的,这个调用:

On the other hand, as you've observed, this call:

f.operator()<true>();  // ok

很好,因为您正在为 foperator() 指定模板参数,这确实是一个模板.

is fine, because you are specifying the template argument for f's operator() which is indeed a template.

此外,此问题与 lambda 的非类型模板参数无关,如果它也是类型模板参数,也会发生同样的情况.

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.

这篇关于带有非类型模板参数的 C++20 lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 10:08