c++11 lambda expression acting on traditional C callback function

Source: Internet
Author: User

--std=c++11#include <functional> #include  <cstdio>typedef bool  (*is_x_num) ( int); Void show_x_num (Int * array, int len, is_x_num is_x_num) {     for (int i = 0; i < len; i++)  {         if (Is_x_num (array[i))  {             printf ("%d ",  array[i]);        }     }    printf ("\ n");} VOID&NBSP;SHOW_X_NUM2 (int * array, int len, std::function<bool (int) > is_x_ num) {    for (int i = 0; i < len; i++)  {         if (Is_x_num (array[i))  {             printf ("%d ",  array[i]); &NBSP;&Nbsp;      }    }    printf ("\ n");} Int main ()  {    int list[] = { 2, 3, 5, 8,  19, 20, 21 };    printf ("show all:\t");     Show_x_num (list, 7, [] (int) {return true;});     printf ("show even num:\t");     show_x_num (List, 7,  [] (int a) {return ! ( A&NBSP;%&NBSP;2);});     int two = 2;    printf ("Show even num:\t" );     //show_x_num (list, 7, [=] (int a) {return ! ( A % two);});     //error: cannot convert  ' main ():: __lambda2 '  to  ' is_x_num  {aka bool  (*) (int)} '  for argument  ' 3 '  to  ' Void show_x_num (int*,  int, is_x_num) '     show_x_num2 (list, 7, [=] (int a) {return ! ( A % two);});     return 0;}

In the above example, the 3rd parameter of Show_x_num is a traditional function pointer, and we can use a lambda expression without capture ([Captrue]) as the 3rd parameter of the Show_x_num ( section Lines 31 and 34), but using a lambda with capture will compile an error (line 39 ).

If you want to use a captured lambda, declare the function parameter as std::function<> (line 17th), and line 42nd uses the captured lambda to succeed.

This is the case (a lambda expression with a capture cannot be converted to a traditional function pointer), and I understand that a lambda with a capture actually adds parameters.


c++11 lambda expression acting on traditional C callback function

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.