2

I have a Visual Studio 2008 C++03 project where I would like to use a boost::function object to set the value of a pointer. Something like this:

boost::function< void( int* ) > SetValue;
boost::function< int*() > GetValue;

int* my_value_;
SetValue = boost::bind( my_value_, _1 ); // how should this look?
GetValue = boost::bind( my_value_ ); // and this?

int v;
SetValue( &v );
assert( my_value_ == &v );

int* t = GetValue();
assert( t == my_value_ );

Is there a way to do this or do I need an intermediate function like:

void DoSetValue( int* s, int* v ) { s = v; };
SetValue = boost::bind( DoSetValue, my_value_, _1 );

Thanks

PaulH
  • 7,759
  • 8
  • 66
  • 143

3 Answers3

2

Use Boost.Lambda library:

#include <boost/function.hpp>
#include <boost/lambda/lambda.hpp>

int main()
{
    boost::function<void(int*)> SetValue = (boost::lambda::var(my_value) = boost::lambda::_1);
    boost::function<int*()> GetValue = boost::lambda::var(my_value);
}

You can find more about using variables in its documentation.

Rafał Rawicki
  • 22,324
  • 5
  • 59
  • 79
1

Your first attempt will not work as bind() requires a function (or functor), but you are passing a data pointer, so you need to provide a function that does the work you seek.

Note: if you use C++11, you could use lambdas, to avoid having to create a named function

Note: you need to dereference the pointers in DoSetValue or use references (in which case you need to change the declaration of SetValue as well) -- otherwise the change will not be visible outside the function call

void DoSetValue( int& s, int& v ) { s = v; }; 
Attila
  • 28,265
  • 3
  • 46
  • 55
0

For bind to work that way, you would need a pointer to operator=( int* ). Of course, there is no such thing, so you need an intermediate function.

If you could use lambda or phoenix, there are ways to make a function-object that assigns something to something else. It depends on which library you use, but it would look somewhat like this:

bl::var( my_value_ ) = bl::_1;
K-ballo
  • 80,396
  • 20
  • 159
  • 169
  • boost::phoenix looks like it could be a good solution, but I'm having trouble understanding from the docs how to use it in this situation. For example: `SetValue = boost::phoenix::val( my_value_ );` doesn't seem to do anything when SetValue() is invoked later. – PaulH May 23 '12 at 19:04
  • Try something like `boost::phoenix::val( my_value_ ) = phoenix_placeholder::_1` – K-ballo May 23 '12 at 19:09
  • Yes, but how do I get that in to the function pointer `SetValue`? – PaulH May 23 '12 at 19:13
  • Doesn't just `SetValue = ( boost::phoenix::val( my_value_ ) = phoenix_placeholder::_1 )` works? – K-ballo May 23 '12 at 19:14
  • It compiles and runs, but has no effect on the value. – PaulH May 23 '12 at 19:45