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

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

    A C++ lambda can capture "outside" variables. [Edit: when I first read the question, I somehow missed where he mentioned that he's aware of lambdas. For better or worse, C++ doesn't have anything else that really resembles an anonymous class].

    For example:

    #include 
    
    int main(){ 
    
        int y = 100;
        auto lambda = [=](int x) { return x + y; };
    
        std::cout << lambda(2);
    }
    

    ...prints 102 as its output.

    Note that although it looks somewhat like a function, a C++ lambda really results in creating a class. I suppose I should add: that class isn't technically anonymous, but it has some unspecified name that's never directly visible.

    Edit: I'm still a bit puzzled about the justification for not using lambdas though. Is the intent to use one class that contains many member functions? If so, it's not clear how you plan to specify which member function to invoke at which time/for which purpose. My immediate reaction is that this sounds suspiciously as if you're trying to twist the language to support a problematic design.

提交回复
热议问题