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

后端 未结 5 595
挽巷
挽巷 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条回答
  •  梦毁少年i
    2020-12-23 14:41

    You can capture the variable manually (which is similar to what a lambda capture does behind the scenes):

    int main() {
        int y = 100;
        struct { 
            int& y;
            int operator()(int x) { return x + y; }
        } anon = { y };
    }
    

    You can then use it like this:

    #include 
    ...
    std::cout << anon(10) << std::endl;
    

    Prints 110 as expected. Unfortunately you can't have the anonymous type inherit from another with this method as initializer-list constructable types can't inherit from another type. If inheritance is crucial then you should use the constructor method outlined by Andy Prowl.

提交回复
热议问题