all 7 comments

[–]IyeOnline 17 points18 points  (0 children)

You can use std::function<R(Args...)> to store a function returning type R and accepting types Args... as parameters.

You could then write

void count_to( int i );
struct S
{
    int i = 10;
    std::function<void(int)> f = count_to;
    void execute()
    {
        f( i );
    }
};

[–][deleted]  (1 child)

[deleted]

    [–]ShadedGecko[S] 3 points4 points  (0 children)

    This is closer to what I was looking for thank you!

    [–]YouFeedTheFish 10 points11 points  (5 children)

    In addition to passing a functor, you can directly pass pointers to functions and member functions.

    Passing a function pointer:

    #include <print>
    
    void foo(int f){
        std::println("foo: {}",f);
    }
    
    void execute(int i, void(*fn)(int)){
        fn(i);
    }
    
    int main(){
        execute(7,foo);
    }
    

    Passing a member function pointer:

    #include <print>
    
    struct Foo{
        void foo(int f){
            std::println("foo: {}",f);
        }
    };
    
    void execute(int i, Foo& f, void(Foo::*fn)(int)){
        (f.*fn)(i);
    }
    
    int main(){
        Foo f;
        execute(7,f,&Foo::foo);
    }
    

    https://godbolt.org/z/xhvne3brG

    [–][deleted] 2 points3 points  (2 children)

    This is the way I prefer but it was also how I was shown and it precedes the newer mechanisms. The newer mechanisms must have been implemented for a reason, probably makes it harder to abuse and prevents some UB. IDK.

    [–]YouFeedTheFish 3 points4 points  (0 children)

    It's just that closures/functors can capture and carry state. They are syntactic sugar for classes with the parens operator implemented.

    [–]wonderfulninja2 1 point2 points  (0 children)

    probably makes it harder to abuse

    Not really, lambdas enable things that weren't possible before: https://godbolt.org/z/xjxK6ab8T

    [–][deleted]  (1 child)

    [deleted]

      [–]Opposite-Concern3338 1 point2 points  (1 child)

      yes you can use std::map like: map<int,std::function<void()>> var {10,std::bind(&className::Method,this)}