Boost logo

Boost Users :

From: Stuart Dootson (stuart.dootson_at_[hidden])
Date: 2006-01-24 12:19:55


On 1/24/06, David A. Greene <greened_at_[hidden]> wrote:
> David A. Greene wrote:
> > I'm having some trouble with BLL and Boost.Function in this simple
> > testcase:
>
> I worked around the problem using Boost.Function:
>
> int main(void)
> {
> Test tester;
> int value = 10;
>
> boost::function<void (int)> bound = boost::lambda::bind(&Test::foo,
> &tester, boost::lambda::_1);
> Caller<boost::function<void (void)> >
> printer(boost::lambda::bind(bound, value));
> //Caller<boost::function<void (void)> >
> printer(boost::lambda::bind(boost::lambda::bind(&Test::foo, &tester,
> boost::lambda::_1), value));
>
> printer.bar();
>
> return(0);
> }
>
> I have a couple of questions and another problem, however.
>
> I had to pass "&tester" to the first bind expression because g++
> complained about passing "tester" as "const Test &." Is passing by
> reference supposed to work?

Only if you use a reference wrapper - i.e. you can use
boost::ref(tester) or boost::lambda::var(tester) rather than &tester

>
> Also, this workaround gets rid of the error but is the original code
> supposed to work as written or did I do something incorrectly?
>
> Finally, the new problem, closer to the actual code I'm working with:
>
> #include <boost/lambda/bind.hpp>
> #include <boost/function.hpp>
> #include <boost/shared_ptr.hpp>
>
> #include <iostream>
>
> class Test {
> public:
> void foo(int a) { std::cout << "a is " << a << std::endl; };
> };
>
> template<typename Function>
> class Caller {
> private:
> Function func;
>
> public:
> Caller(Function f) : func(f) {};
>
> void bar(void) { func(); };
> };
>
> int main(void)
> {
> boost::shared_ptr<Test> tester(new Test);
> int value = 10;
>
> boost::function<void (int)> bound = boost::lambda::bind(&Test::foo,
> tester, boost::lambda::_1);
> Caller<boost::function<void (void)> >
> printer(boost::lambda::bind(bound, value));
>
> printer.bar();
>
> return(0);
> }
>

If you're using a shared_ptr, you'll either need to use tester.get()
directly to get a Test* to pass into the bind expression

   bind(&Test::foo, tester.get(), value)

or something like

   bind(&Test::foo, bind(boost::shared_ptr<Test>::get, tester), value)

to delay the call to tester.get() until invocation of printer.bar().

Stuart Dootson


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net