接受lambda函数和函数指针作为参数

use*_*501 0 c++ lambda function-pointers function

我有一个功能,比方说

void processSomething(Arg1 arg1, Function t){
    ...
    t(someVariable);
}
Run Code Online (Sandbox Code Playgroud)

我希望以下两种用法都能正常工作:

processSomething(myArg1, [&](SomeVariable someVar){...});
void(*myFunc)(void) = &someFunc;
processSomething(myArg1, myFunc);
Run Code Online (Sandbox Code Playgroud)

但是,我发现在使用void(*myFunc)(void)参数声明时我不能使用lambda-way .有没有两个单独的函数或过于复杂的包装器使用两种用法的方法?

Ded*_*tor 6

那么,你有两个选择:

  1. 模板:

    template<class F>
    void processSomething(Arg1 arg1, F t){
    
    Run Code Online (Sandbox Code Playgroud)

    这是首选方法,因为它可以创建更高效​​的代码,但代价是可能的代码重复.

  2. 使用一个std::function或这样的:

    void processSomething(Arg1 arg1, std::function<void(SomeVariable)> t){
    
    Run Code Online (Sandbox Code Playgroud)

    所涉及的间接性存在运行时成本,但在每种情况下它将使用相同的代码.