Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2003-02-19 09:37:01


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. :-)


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