Can I create anonymous classes in C++ and capture the outside variables like in Java?

后端 未结 5 604
挽巷
挽巷 2020-12-23 13:52

In Java, when I need a callback function, I have to implement an anonymous class. Inside the anonymous class, I can access the outside variables if they\'re final

5条回答
  •  星月不相逢
    2020-12-23 14:30

    If your IA class really has just one virtual method that you need to override (and the real complexity is other non-virtual methods) but you don't want to capture the local variables that this method needs, how about this:

    int main() {
      int y = 100;
      auto f = [=](int x){return x+y;};
      typedef decltype(f) F;
      struct IB : IA {
        F _f;
        IB(F _f): _f(_f) {}
        int f(int x) { return _f(x); }
      } a(f);
      doFancyWork(&a);
      return 0;
    }
    

提交回复
热议问题