Boost logo

Boost :

From: Matthias Hoffrichter (TrollCoder_at_[hidden])
Date: 2003-02-23 11:29:36


Hi!

I can't make SetEventHandler to a free/global function because the
EventFunction that boost::bind created should be added to a private std::map
of CWindow. Or I need an extra member method that only adds the
boost::function to the map. But it now works with a static_cast in
SetEventHandler how Sam suggested. :)
At the moment I am contented with the interface of SetEventHandler, but
maybe I have to change it later. Time will reveal. ;-)

Thanks Peter, thanks Douglas.

cu,
Matthias

----- Original Message -----
From: "Peter Dimov" <pdimov_at_[hidden]>
To: "Boost mailing list" <boost_at_[hidden]>
Sent: Wednesday, February 19, 2003 3:37 PM
Subject: Re: [boost] Encapsulate boost::bind in a template method

> Matthias Hoffrichter wrote:
> > Hi,
> >
> > I want to encapsulate boost::find in a template method in a base
> > class for easier use.
> > Here is some code:
> >
> > #include <boost/function.hpp>
> > #include <boost/bind.hpp>
> >
> > class CWindow {
> > public:
> > CWindow() {
> > SetEventHandler(&CWindow::OnCreate); // this call works
> > }
> > long OnCreate() {
> > return 0;
> > }
> > template<typename T> void SetEventHandler(long (T::*Function)()) {
> > boost::function<long> EventFunction = boost::bind(Function, this);
> > // ...
> > // Add EventFunction into a std::map
> > }
> > };
> >
> > class CButton : public CWindow {
> > public:
> > CButton() {
> > SetEventHandler(&CButton::OnPaint); // this call doesn't compile
> > }
> > long OnPaint() {
> > return 0;
> > }
> > };
>
> In CWindow::SetEventHandler<CButton>, 'this' is a CWindow*. You can't
invoke
> CButton::OnPaint using a pointer to CWindow.
>
> The easiest solution is probably to make SetEventHandler a free function:
>
> template<class F, class T> void setEventHandler(F f, T * p)
> {
> boost::function<long> EventFunction = boost::bind(f, p);
> // ...
> // Add EventFunction into a std::map
> }
>
> and then simply use setEventHandler(&CButton::OnPaint, this) in
> CButton::CButton().
>
> You'll soon find that this is not _that_ easier to use compared to
>
> setEventHandler(bind(&CButton::OnPaint, this));
>
> and the latter is much more flexible:
>
> setEventHandler(bind(&CButton::OnMessage, this, WM_PAINT));
>
> but that's another story. :-)
>
> _______________________________________________
> Unsubscribe & other changes:
http://lists.boost.org/mailman/listinfo.cgi/boost


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk