c++functionboostbinders

lightweight boost::bind


I'm so sick of the pass-callback-data-as-void*-struct anti-pattern. Boost bind solves it nicely, but is an unacceptable dependency. What's a lightweight alternative? How would I write it myself as simply as possible?


Solution

  • I'm not familiar with boost:bind, but is it something like this?

    #include <iostream>
    
    void foo (int const& x) {
        std::cout << "x = " << x << std::endl;
    }
    
    void bar (std::string const& s) {
        std::cout << "s = " << s << std::endl;
    }
    
    template<class T>
    void relay (void (*f)(T const&), T const& a) {
        f(a);
    }
    
    int main (int argc, char *argv[])
    {
        std::string msg("Hello World!");
        relay (foo, 1138);
        relay (bar, msg);
    }
    

    Output --

    x = 1138
    s = Hello World!