Dean
Dean

Reputation: 6950

Generic C++14 lambdas and relationship with templates

I did read that C++14 generic lambdas with auto parameters are actually templates, so the following is valid C++14

auto glambda = [] (auto a) { return a; };
cout << glambda(23); // Prints 23
cout << glambda('A'); // Prints A

This doesn't quite stack up with what I know from templates.. where's the instantiation point? What is it stored in the glambda variable if the first call instantiates a template with int and the second one with char?

Upvotes: 4

Views: 154

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 476970

It's not that the "lambda is a template" -- that doesn't make sense, a lambda is an expression. Rather, the type of the closure object that's defined by the lambda expression has an overloaded function call operator that is defined by a member function template. So the instantiation point is the first use of the respective call operator.

In other words, a lambda [a, &b](auto x, auto y) -> R { /* ... */ } has a type like:

struct __lambda
{
    __lambda(const A & __a, B & __b) : a(__a), b(__b) {}

    template <typename T1, typename T2>
    R operator()(T1 x, T2 y) const { /* ... */ }

private:
    A a;
    B & b;
};

Upvotes: 8

Guillaume Racicot
Guillaume Racicot

Reputation: 41760

A generic lambda is an object of a compiler generated type that has a template method called operator(). Your code can be rewritten with this equivalent:

struct MyLambda {
    template<typename T>
    T operator() (T val) {
        return val;
    }
};

int main() {
    MyLambda func;

    std::cout << func('A');
    std::cout << func(42);
}

The compiler will instantiate operator() when needed.

Hope it helped

Upvotes: 4

Related Questions