Boost logo

Boost :

From: Greg Colvin (Gregory.Colvin_at_[hidden])
Date: 2003-03-04 11:51:45


template<typename T,T* p,void (T::*f)(int)>
   void callback(int i) { (p->*f)(i); }

At 08:02 AM 3/4/2003, Marc Jacobs wrote:
>I'm trying to use a member function as a callback to a C-style library. I've
>got the bind working by itself, but the resulting function object does not
>convert to the type required by the library. Clearly a boost::bind object is
>not a simple function pointer and the type is being checked by the compiler.
>Is there any way to coerce the types and still use boost::bind? I have no
>control over the declaration or definition of the C-style library. Here's a
>sample:
>
>#include <boost/bind.hpp>
>#include <iostream>
>#include <string>
>
>using namespace boost;
>using namespace std;
>
>typedef void (*callback_type)( int i );
>
>// the C-style library function
>void caller( callback_type callback )
>{
> callback( 501 );
>}
>
>// normal usage
>void simple_callback( int i )
>{
> cout << i << endl;
>}
>
>// attempting to use member function as callback
>struct member_callback
>{
> explicit member_callback( const string & prefix ) :
> prefix_( prefix )
> {}
>
> void callback( int i )
> {
> cout << prefix_ << i << endl;
> }
>
>private:
> string prefix_;
>
>};
>
>int main( int argc, char * argv[] )
>{
> caller( simple_callback ); // works
>
> member_callback mc( "info: " );
> caller( bind( &member_callback::callback, ref( mc ), _1 ) ); // error!
>
> return 0;
>}
>
>It fails to compile with the following message:
>
>callback.cpp: In function `int main (int, char **)':
>callback.cpp:45: cannot convert `boost::_bi::bind_t<void,
>boost::_mfi::mf1<void, member_callback, int>,
>boost::_bi::list2<boost::reference_wrapper<member_callback>,
>boost::arg<1> > >' to `void (*) (int)' for argument `1' to `caller
>(void (*) (int))'
>make: *** [/tmp/marcja/callback/1.0/dbg/obj/callback.o] Error 1
>
>I'm using gcc 2.96 on Red Hat 7.1 with boost 1.29.0.
>Marc
>
>
>
>_______________________________________________
>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