Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke a lambda template?

I was able to compile the following code with gcc:

template<typename... Pack>
auto func(Pack... x) {
    return (x + ...) ;
}

template<typename... Pack>
auto lamd = [](Pack... x) {
    return (x + ...) ;
};

I can invoke the function template with func(1,2,3), but I get an error when invoking a the lambda, with lamd(1,2,3) or lamd<int>(1,2,3).

like image 713
Nujufas Avatar asked Dec 18 '22 16:12

Nujufas


1 Answers

For lambdas, you can make it generic lambda with the usage of auto.

auto lamd = [](auto... x) {
    return (x + ...) ;
};

Since C++20 you can uses an explicit template parameter list, but note that the template parameter list is still used with the operator() of the lambda, just as the usage of auto parameters. e.g.

auto lamd = []<typename... Pack>(Pack... x) {
    return (x + ...) ;
};

and then you can call it as lamd(1,2,3).

LIVE

like image 163
songyuanyao Avatar answered Dec 20 '22 07:12

songyuanyao