Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

#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? It would be a disappointing limitation, as I thought the intention was to make lambdas able to do as much as templates.

like image 644
ThreeStarProgrammer57 Avatar asked Dec 30 '22 19:12

ThreeStarProgrammer57


1 Answers

Is explicitly passing template arguments at the lambda call site forbidden?

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.

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.

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.

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.

like image 196
cigien Avatar answered Jan 03 '23 05:01

cigien