Lightweight boost :: bind

I'm so tired of the pass-callback-data-as-void * -struct anti-pattern method. Boost bind solves this well, but is an unacceptable dependency. What is an easy alternative? How could I write this as simple as possible?

+5
source share
7 answers

I am 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);
}

Exit -

x = 1138
s = Hello World!
+2
source

Firstly, I doubt your claim that it is too hard for you.

Secondly, roll up your own template if you need to control behavior.

Thirdly, if you are afraid to roll your own template, I doubt your ability to judge that is boost::bindtoo heavy for you.

+17

Don Clugston. , -, , ( 2 .) 1.4+ Boost.Bind.

+7

++ - (.. , operator()). , , , , . , boost:: bind / < > , , .

, :

typedef void (*cb)(void*);
void funcThatNeedsCallback(cb thecallback, void *thedata) {
    // blah blah
    thecallback(thedata);
}

:

template<typename T>
void funcThatNeedsCallback(T &thefunctor) {
    // blah blah
    thefunctor();
}

:

struct MyFunctor {
    int mydata1;
    char *mydata2;
    void operator()(void) {
        // do something with mydata1 and mydata2
    }
};

MyFunctor mf = { value1, value2 };
funcThatNeedsCallback(mf);

, , .

(, funcThatNeedsCallback - , ), , , :

class CallbackInterface {
    virtual void theCallback(void) = 0;
    virtual ~CallbackInterface() {} // just in case
};

void funcThatNeedsCallback(CallbackInterface &cb) {
    // blah blah
    cb.theCallback();
}
+2

Boost.Function 1.34 boost:: bind. boost, , . boost::function , , ( ).

. : http://lists.boost.org/Archives/boost/2006/01/98993.php.

+2

libsig++. - LGPL, - , Boost.Signal( " ", , " Boost ", "Boost.Signal " ).

+1

The people behind boost :: binds speed probably never wrote low latency trading systems or high speed graphics libraries.
Boost is a good general purpose library, not speed optimized. Some additional libraries (compared to customized implementations) can be quite slow in comparison.

For functions / delegates, see http://www.codeproject.com/KB/cpp/fastdelegate2.aspx for a useful comparison.

Ciao.

+1
source

All Articles