Boost logo

Boost :

From: Giovanni Bajo (giovannibajo_at_[hidden])
Date: 2002-04-10 13:17:47

Is there a way to chain two functions? Yes, we can use boost::compose (or
nested boost::bind) to "compose" two functions, but we can't just chain
For example:

***** BEGIN ******
void Print(int n)
{ cout << n << endl; }

boost::function<void> f1 = boost::bind(Print, 1);
boost::function<void> f2 = boost::bind(Print, 4);

boost::function<void> f = f1 + f2;

f(); // will print "1" and "4". The same of calling f1 and then f2.
***** END ******

Using operator+ is just an example, it's ok boost::concatenate() or
whatever. This should also work for functions with parameters, by
concatenating them:

***** BEGIN ******
boost::function<void, int, float> f1;
boost::function<void, double, bool> f2;

boost::function<void, int, float, double, bool> a = f1 + f2;
boost::function<void, double, bool, int, float> b = f2 + f1;
boost::function<void, bool, double, float, int> c = boost::bind(f1+f2, _4,
_3, _2, _1); // reverse parameter order
***** END ******

What about temporary objects? They should work as well.

***** BEGIN ******
boost::function<void, int, float> f1;
boost::function<void, double, bool> f2;

(f1+f2)(3, 4.5f, 5.0, true);
***** END ******

About return types, I'm a bit more fuzzy. Several random ideas, some of
which are ugly to me as well, but I'll just thrown them anyway:

***** BEGIN ******
boost::function<int> f1;
boost::function<float> f2;

// If we select void, it means we will ignore the return values.
boost::function<void> a = f1 + f2; // correct

// If we select any of the type, it could return only that value
boost::function<float> a = f1 + f2; // correct, returns f3's return value

// Let's bring our good ol' tuples into the game:
boost::function<boost::tuple<int,float> > a = f1 + f2; // return both
return values
***** END ******

Also, I'm not sure what should be the return value for an unnamed object.

***** BEGIN ******
boost::function<int> f1;
boost::function<float> f2;

// What's the type of this expression? Maybe a tuple<int,float> is the most
(f1+f2)(4, 5.0f);
***** END ******

Let me know what you think about it. Also, I don't have a clue about
internals of boost::function, so I apologize in advance if I've overlooked

Giovanni Bajo

Boost list run by bdawes at, gregod at, cpdaniel at, john at