Boost logo

Boost Users :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2003-09-10 06:21:49


Darren Vincent Hart wrote:
> Boost gurus,
>
> I am using boost::bind in combination with boost::signals for a GUI
> toolkit. The signals return bool for convenience, but it is often
> desireable to bind a void function and connect it to a signal. Is
> there a convenient way to assign a return value for a void function.
>
> As an example:
>
> -----------------------------------------------------------------
>
> struct panel
> {
> void print() { std::cout << "print" << std::endl; }
> }
>
> struct widget
> {
> boost::signal<bool ()> on_event;
> }
>
> panel p;
> widget w;
>
> // is there some way to do something like this?
> w.on_event.connect(boost::bind_return(panel::print, &p, true));

You can do this with Lambda:

using namespace boost::lambda;

    w.on_event.connect( (bind(panel::print, &p), true) );

but not with boost::bind, sorry.

Not out of the box, anyway.

template<class F, class V> class override_return_t
{
private:

    F f_;
    V v_;

public:

    typedef V result_type;

    override_return_t(F const & f, V const & v): f_(f), v_(v)
    {
    }

    result_type operator()()
    {
        f_();
        return v_;
    }

    result_type operator()() const
    {
        f_();
        return v_;
    }
};

template<class F, class V> override_return_t<F, V> override_return(F const &
f, V const & v)
{
    return override_return_t<F, V>(f, v);
}

#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <iostream>

void g()
{
    std::cout << "g()\n";
}

int main()
{
    boost::function<bool()> f = override_return(boost::bind(g), true);
    std::cout << f() << std::endl;
}

You can even go a bit further and bring boost::bind one step closer to its
lambda counterpart:

template<class R, class F, class L, class V>
override_return_t<boost::_bi::bind_t<R, F, L>, V>
operator,(boost::_bi::bind_t<R, F, L> const & f, V const & v)
{
    return override_return_t<boost::_bi::bind_t<R, F, L>, V>(f, v);
}

int main()
{
    boost::function<bool()> f = (boost::bind(g), true);
    std::cout << f() << std::endl;
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net