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

后端 未结 5 598
挽巷
挽巷 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:45

    There is no way to automatically capture those variables, but you can use an alternative approach. This is if you want to capture by reference:

    int main() {
        int y = 100; // mark y as final if possible
        class IB : public IA {
        public:
          IB(int& y) : _y(y) {}
          int f(int x) { return x + _y; }
        private:
          int& _y;
        } a (y);
        return 0;
    }
    

    If you want to capture by value, just change int& into int.

    Anyway, you may consider using a tuple of lambdas as a "multi-callback" object if that is what bothers you about individual lambdas. You would still have everything packed in one object and capturing would be done for free.

    Just as an example:

    auto callbacks = make_tuple(
        [] (int x) { cout << x << endl; },
        [&] () { cout << y << endl; }, // y is captured by reference
        [=] (int x) { cout << x + y << endl; }, // y is captured by value
        // other lambdas here, if you want...
        );
    

提交回复
热议问题