Generic C ++ 14 lambdas and template relationships

I read that the common lambdas C ++ 14 characters with parameters autoare actually patterns, 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 exactly match what I know from the templates .. where is the point of creation? What is stored in the variable glambdaif the first call creates an instance of template c intand the second calls c char?

+4
source share
2 answers

, " - " - , - . , , , , -. , .

, lambda [a, &b](auto x, auto y) -> R { /* ... */ } :

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;
};
+8

, operator(). :

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

int main() {
    MyLambda func;

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

operator().

,

+4

All Articles