如何存储仿函数以供以后在 C++ 中调用

How to store a functor for later invocation in C++

这个问题可能比较幼稚,学习中还请见谅

请考虑以下类 C++ 伪代码:

#include <iostream>
#include <string>
#include <functional>


struct A{
    bool doSomething(int in){
        std::cout<<"SOMETHING WAS DONE THAT DAY: "<<in<<std::endl;
        return true;
    }
};

struct B{
    std::function executor;

    void setExecutor(std::function f){
        executor=f;
    }

    bool doSomethingLater(int in){
        return executor(in);
    }
};

static bool yoloFunction(int in){
    std::cout<<"LIVING LA VIDA LOCA: "<<in<<std::endl;
    return false;
}


int main()
{
  A myExecutor;
  B lazyAss;

  // Storing member function for later invocation
  lazyAss.setExecutor(&myExecutor::doSomething);
  bool result_1 = lazyAss.doSomethingLater(1337);
  std::cout<<"The first result is "<<result_1<<std::endl;

  // Storing regular function for later invocation
  lazyAss.setExecutor(&yoloFunction);
  bool result_3 = lazyAss.doSomethingLater(42);
  std::cout<<"The second result is "<<result_2<<std::endl;

  // Storing lambda function for later invocation
  lazyAss.setExecutor([=](int in){
    std::cout<<"P- P- P- POKERFACE!: "<<in<<std::endl;
    return true;
  });
  bool result_3 = lazyAss.doSomethingLater(666);
  std::cout<<"The third result is "<<result_3<<std::endl;

}

它应该说明我正在努力完成的事情,即 存储某种回调以供以后调用

那么,在不使用 boost 或其他非标准依赖项的情况下,我将如何以最简单的方式在现代 C++ 中执行此操作?

有哪些选项和注意事项?

需要注意的是,回调的签名是预先知道的,不会改变。

此外,我要存储的回调可能具有不同的形式,例如独立函数、成员函数或 lambda。

像这样修改结构 B:

struct B {
    std::function<bool(int)> executor;

    void setExecutor(std::function<bool(int)> f) {
        executor = f;
    }

    bool doSomethingLater(int in) {
        return executor(in);
    }
};

在 main() 中,使用 lambda 将成员函数作为参数传递,如下所示:

lazyAss.setExecutor([&](int i)->bool { return myExecutor.doSomething(i); });