Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C++ (http://www.velocityreviews.com/forums/f39-c.html)
-   -   Strange boost::bind behavior (compile) (http://www.velocityreviews.com/forums/t587672-strange-boost-bind-behavior-compile.html)

Kira Yamato 01-28-2008 02:54 AM

Strange boost::bind behavior (compile)
 
#include <iostream>
#include "boost/bind.hpp"

using namespace std;
using namespace boost;

int sum3(int x, int y, int z) { return x+y+z; }

int sum2(int x, int y) { return x+y; }

int sum1(int x) { return x; }

int main()
{
// Let's try some standard example uses of boost::bind first.

// Ex 1: prints 1.
cout << (bind(sum1, _1))(1) << endl;

// Ex 2: prints 11.
cout << (bind(sum2, _1,_2))(1,10) << endl;

// Both Ex 1 and Ex 2 works as advertised. However,

// Ex 3: (won't compile!)
cout << (bind(sum3, _1,_2,_3))(1,10,100) << endl;

// The above Ex 3 fails to compile. What did I do wrong?

// Let's try some nested uses of boost::bind below.

// Ex 4: prints 11.
cout << (bind(sum2, bind(sum1, _1), bind(sum1, _2)))(1,10) << endl;

// Ok, Ex 4 is functionally equivalent to Ex 2.
// But it's still cool to see that placeholders can span across bind's.
// Hmm. I wonder if I can span placeholders arbitrarily. So,
I attempted ...

// Ex 5: (won't compile!)
cout << (bind(sum2, bind(sum2, _1,_2), bind(sum2,
_3,_4)))(1,10,100,1000) << endl;

// I guess I was asking for too much.
// The resulting bind object will not accept 4 arguments.
// However, when I tried ...

// Ex 6: prints 22.
cout << (bind(sum2, bind(sum2, _1,_2), bind(sum2,
_1,_2)))(1,10) << endl;

// So, I hypothesize that boost looks at the leading bind
object to determine
// the maximum number of arguments to accept.
// In this case, the leading bind object was sum2(int, int).
// So, it only accepts at most 2 arguments.

// If my hypothesis is right, then I expect the following to
*not* compile:

// Ex 7: prints 11.
cout << (bind(sum1, bind(sum2, _1,_2)))(1,10) << endl;

// The leading bind is sum1(int) taking 1 argument.
// But Ex 7 still compiles and runs just fine, even though I
passed to it 2 arguments.
// At this point, I'm somewhat confused.

// My question to this newsgroup is this:
// Does anyone know the precise rule on
// how boost::bind figures out how many arguments to accept?

// Note: I am using g++4.0.1 and boost 1.34.1.

return 0;
}

//--

//-kira



All times are GMT. The time now is 09:26 PM.

Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57