logical_and, boost::bind, and boost::function

I'm trying to use boost::bind and boost::function with std::logical_not and I've run into some strange template magic that I don't understand. In the example below, I use boost::function to help compose several boost::bind calls so that I don't have to do it all on one line (I find that this improves readability). The problem is that when I do this, the functions that are bound with boost::bind never get called. They will get called only if I construct everything on one line. (???) Is this expected behavior? If so, why does it work like this? Thanks, aaron #include <algorithm> #include <functional> #include "boost/bind.hpp" #include "boost/function.hpp" using namespace std; using namespace boost; class test { public: void bindtest() { // test1: composed gradually for clarity // function<bool ()> funcFoo = bind(&test::foo, this); function<bool ()> funcBar = bind(&test::bar, this); function<bool ()> funcTest1= bind(logical_and<bool>(), funcFoo, funcBar); // doesn't call test::foo or test::bar! (returns true) bool test1= funcTest1(); cout << "test1= " << test1 << endl; // test2: composed directly on one line function<bool ()> funcTest2= bind(logical_and<bool>(), bind(&test::foo, this), bind(&test::bar, this) ); // calls test::foo and test::bar (returns false) bool test2= funcTest2(); cout << "test2= " << test2 << endl; } bool foo() { cout << "foo" << endl; return false; } bool bar() { cout << "bar" << endl; return false; } };

On Aug 10, 2005, at 11:44 AM, Simmons, Aaron wrote:
function<bool ()> funcFoo = bind(&test::foo, this); function<bool ()> funcBar = bind(&test::bar, this); function<bool ()> funcTest1= bind(logical_and<bool>(), funcFoo, funcBar);
Alan's post made me realize what's happening. Indeed, this last bind() doesn't know that funcFoo and funcBar are functions that it should call. You can tell it to consider them as functions by calling bind() on them: function<bool ()> funcTest1= bind(logical_and<bool>(), bind(funcFoo), bind(funcBar)); Now it should work fine. Whether it's actually clearer or not is for you to decide, but here's one warning: each call through a boost::function object is like a virtual function call. So by turning each call to one boost::function object into a call through 3 boost::function objects, there will be a performance penalty. Doug
participants (2)
-
Douglas Gregor
-
Simmons, Aaron