Is it possible to recreate such Java code in C ++ :

class Clazz { public void method(type arg) { } } interface Method { public void im(type arg); } public void run( Method m) { m.im(actualArg); } Clazz obj1 = new Clazz (); Clazz obj2 = new Clazz (); // передать obj1.method run(new Method() { public void im(type arg) { obj1.method(arg); } ); // передать obj2.method run(new Method() { public void im(type arg) { obj2.method(arg); } ); 

I mean that the function is passed as an argument , but also to declare it directly in the argument , without creating it separately and passing the reference to it as an argument. I am interested in whether there is such an opportunity in C ++ (in Java ), if not, I will pass the function as a link. Or maybe there is a better solution? I would be grateful for the advice and guidance.

    1 answer 1

    Are you not about lambda expressions?
    Type:

     int doit(int x, int f(int)) { return f(x); } int main(int argc, const char * argv[]) { cout << doit(5,[](int x){ return 2*x; }) << endl; cout << doit(2,[](int x){ return x*x; }) << endl; } 

    Those. in doit is not a pointer to a certain function that is passed, but its definition immediately?

    • Thank you very much, never interested in lambda expressions, it turns out that nothing. I read about them and this is exactly what you need. - Andriy Hopta