Early adopters of C ++ 14: Generic Lambdas (Generic lambda) and lambdaslambda

Source: Internet
Author: User

Early adopters of C ++ 14: Generic Lambdas (Generic lambda) and lambdaslambda
The so-called generic lambda is the lambda that uses the auto type indicator specifier in the form parameter declaration. For example

auto lambda = [](auto x, auto y) {return x + y;};
According to the C ++ 14 standard, this lambda serves the same purpose as the following code.
struct unnamed_lambda{  template<typename T, typename U>    auto operator()(T x, U y) const {return x + y;}};auto lambda = unnamed_lambda();
C ++ 14 generic lambda can be seen as an upgraded version of C ++ 11 (single-State) lambda. Single-state lambda is equivalent to a common function object. Generic lambda is equivalent to a function object with template parameters, or a function template with status. Compared with the two, the following results can be released: it can be said that generic lambda greatly enhances the FP (function programming) capability in the C ++ language due to the introduction of single-State lambda.
# Include <iostream> # include <vector> # include <algorithm> using namespace std; int main () {// generic local function auto f = [] (auto x, auto y) {return x + y ;}; cout <f (1, 3) <endl; cout <f (string {}, "abc ") <endl; // generic callback function auto f2 = [] (auto e) {cout <e <"," ;}; vector <int> v1 {1, 2, 3}; vector <string> v2 {"a", "B", "c"}; for_each (v1.begin (), v1.end (), f2 ); cout <endl; for_each (v2.begin (), v2.end (), f2); cout <endl; // generic closure auto f3 = [] (auto) {return [=] () mutable {return a = a + a ;};}; auto twice1 = f3 (1); cout <twice1 () <endl; cout <twice1 () <endl; auto twice2 = f3 (string {"a"}); cout <twice2 () <endl; cout <twice2 () <endl;}/* 4abc1, 2, 3, a, B, c, 24aaaaaa */</string> </int>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.