美文网首页
C++11 lambda 表达式作用在传统C回调函数上

C++11 lambda 表达式作用在传统C回调函数上

作者: 脱水沙丁鱼 | 来源:发表于2019-06-20 09:57 被阅读0次

    作者:赵小刚
    原文:C++11 lambda 表达式作用在传统C回调函数上

    //--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 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]);
            }
        }
        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 % 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;
    }
    

    上面的例子中,show_x_num 的第3个参数是一个传统的函数指针,我们可以使用不带捕获([captrue])的lambda表达式作为show_x_num的第3个参数(第31行和第34行),但使用带捕获的lambda就会编译出错(第39行).

    如果要使用带捕获的lambda,需把函数参数声明成 std::function<> (第17行), 第42行使用带捕获的lambda就成功了.

    之所以会这样(带捕获的lambda表达式无法转化为传统函数指针),我理解带捕获的lambda实际上增加了参数。

    相关文章

      网友评论

          本文标题:C++11 lambda 表达式作用在传统C回调函数上

          本文链接:https://www.haomeiwen.com/subject/cnzrqctx.html