Rajat
Rajat

Reputation: 487

variadic lambda with perfect forwarding

/* The best way to implement lambda (with perfect forwarding) is: */

#include <iostream>
using namespace std;

void func(const char* s) {
    cout << s << endl;
}

// 1st implementation
template <typename... Args>
auto closure = [] (Args&&... args) {
    func(std::forward<decltype(args)>(args)...);
};

// 2nd implementation
auto variadic_lambda = [](auto&&... params) {
    func(std::forward<decltype(params)>(params)...);
};

int main() {
    closure<const char*>("Hello World");
    variadic_lambda("Hello World");
}

/*
 * 2nd implementation
 * struct SomeFunctionObject
 * {
 *     template <typename... Args>
 *     auto operator() (Args&&... args) const;
 * };
 */

While learning C++14 lambda, i came across two ways to create generic lambda (with perfect forwarding). I understand that the second implementation is something like I have shown after main(). But can someone help clear my confusion on what the 1st implementation is? It looks like the underlying closure class itself is a template? Does the 1st implementation also count as variadic lambda?

Upvotes: 0

Views: 310

Answers (2)

bkdm
bkdm

Reputation: 328

Both of them are equivalent. Except for below.

The template version cannot appear inside a function scope. Thus it cannot capture local variables.

The auto version requires c++14 and above but the template one works in c++11

Upvotes: 0

Daniel
Daniel

Reputation: 31579

The 1st implementation is a variable template, for example:

template <typename... Args>
size_t x = sizeof...(Args);

The lambda itself is not generic, there’s a different lambda for each template instantiation.

Upvotes: 2

Related Questions