Reputation: 26335
I am using boost v1.37 on MSVC7. I'm stuck on these old versions and cannot upgrade so please help me work within my means here and do not suggest upgrades as an answer.
I have a class with three member functions. I want to define a boost::function
that can be used to call different member functions on different instances of the same class:
typedef boost::function<bool (unsigned, unsigned)> MyFunc;
The bind would look like:
boost::bind( &A::foo1, _1, _2, _3, boost::ref(some_fixed_param) );
I need to pass the boost::bind
above into a function that takes a MyFunc
as a parameter.
How do I need to setup my boost::function
to take a function object (from boost::bind
) that has the instance object set as a placeholder? How do pass the instance (this
) into the boost::function
? I keep getting compiler errors here so just trying to make sure I understand this properly. Hope I've explained clearly. Thanks in advance.
The real error I get is:
sample.cpp(1156) : error C2664: 'process' : cannot convert parameter 2 from 'boost::_bi::bind_t<R,F,L>' to 'FooFunc &'
with
[
R=bool,
F=boost::_mfi::mf3<bool,A,unsigned int,unsigned int,int>,
L=boost::_bi::list4<boost::arg<1>,boost::arg<2>,boost::arg<3>,boost::reference_wrapper<int>>
]
The code I'm using:
typedef boost::function<bool (unsigned, unsigned)> FooFunc;
class A
{
public:
bool foo1( unsigned s1, unsigned s2, int s3 )
{
}
};
bool process( unsigned s1, FooFunc& foo )
{
unsigned s2 = 100;
A* a; // pretend this is valid
return foo( s1, s2 );
}
void dostuff()
{
int s3 = 300;
process( 200,
boost::bind( &A::foo1, _1, _2, _3, boost::ref( s3 ) ) );
}
Now I know this isn't valid code because in the process()
function I somehow need to call foo
with instance pointer a
. Not sure how to connect the two and not sure why the compiler error is happening.
Upvotes: 0
Views: 2080
Reputation: 2048
First of all, you would need to add a reference to your class to the signature of the boost::function:
typedef boost::function<bool (A *, unsigned, unsigned)> FooFunc;
This does require that class A be declared before this typedef. Then, in your process
function, you can provide this reference when you call the given FooFunc
bool process( unsigned s1, FooFunc foo )
{
unsigned s2 = 100;
A* a = 0; // pretend this is valid
return foo( a, s1, s2 );
}
Note that I also changed the non-const reference to FooFunc to a value parameter. The rest of your code would then work as it is.
I don't have access to MSVC7 (I really do hope you've got 7.1 and not 7.0). You may need to use the 'Portable Syntax' as described in the boost.function documentation, e.g.:
typedef boost::function<bool , A *, unsigned, unsigned> FooFunc;
Upvotes: 3