Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++20 template lambda: how to specify template argument? [duplicate]

Let's say I have a C++20 template lambda:

auto foo = []<bool arg>() {
    if constexpr(arg)
        ...
    else
        ...
};

But how do I call it? I can't seem to find a description of the syntax. I tried the usual foo<true>(); and template foo<true>();, neither of which gcc seems to like.

like image 835
Tom Avatar asked Mar 02 '23 17:03

Tom


1 Answers

foo.template operator()<true>();

is the correct syntax. Try it on godbolt.org

The reason for this strange syntax is because:

  • foo is a generic lambda which implements a template<bool> operator() method.
  • foo.operator()<true>() would interpret < as a comparison operator.

If you want a slightly more readable syntax, try using a std::bool_constant:

auto foo = []<bool arg>(std::bool_constant<arg>) {
    ...
};

foo(std::bool_constant<true>{});

Try it on godbolt.org

like image 96
Patrick Roberts Avatar answered Apr 13 '23 00:04

Patrick Roberts