How to pass and execute anonymous function as parameter in C++11?

后端 未结 3 1799
时光取名叫无心
时光取名叫无心 2020-12-04 10:53

The code I\'m looking for is like following.

bool Func1(int Arg1, C++11LambdaFunc Arg2){
    if(Arg1 > 0){
        return Arg2(Arg1);
    }
}
3条回答
  •  一个人的身影
    2020-12-04 11:24

    First solution:

    You can make your Func1() function a function template:

    template
    bool Func1(int Arg1, T&& Arg2){
        if(Arg1 > 0){
            return Arg2(Arg1);
        }
    
        return false; // <== DO NOT FORGET A return STATEMENT IN A VALUE-RETURNING
                      //     FUNCTION, OR YOU WILL GET UNDEFINED BEHAVIOR IF FLOWING
                      //     OFF THE END OF THE FUNCTION WITHOUT RETURNING ANYTHING
    }
    

    You could then invoke it as you desire:

    int main()
    {
        Func1(12, [](int D) -> bool { return D < 0; } );
    }
    

    Second solution:

    If you do not want to use templates, an alternative (that would bring some run-time overhead) is to use std::function:

    #include 
    
    bool Func1(int Arg1, std::function Arg2){
        if(Arg1 > 0){
            return Arg2(Arg1);
        }
    
        return false;
    }
    

    Once again, this would allow you to call Func1() the way you desire:

    int main()
    {
        Func1(12, [](int D) -> bool { return D < 0; } );
    }
    

提交回复
热议问题