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

Accept both lambda-functions and function-pointers as argument

我有个函数,比方说

void processSomething(Arg1 arg1, Function t){
    ...
    t(someVariable);
}

我希望以下两种用法都有效:

processSomething(myArg1, [&](SomeVariable someVar){...});
void(*myFunc)(void) = &someFunc;
processSomething(myArg1, myFunc);

但是,我发现在使用 void(*myFunc)(void) 作为参数声明时,我无法使用 lambda 方式。 有什么方法可以在没有两个单独的函数或包装器使用过于复杂的情况下同时使用这两种用法?

嗯,你有两个选择:

  1. 模板:

    template<class F>
    void processSomething(Arg1 arg1, F t){
    

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

  2. 使用 std::function 或类似的:

    void processSomething(Arg1 arg1, std::function<void(SomeVariable)> t){
    

    所涉及的间接寻址会产生运行时成本,但在每种情况下都会使用相同的代码。