Reputation: 465
Does boost::bind() bind binds extra arguments as it seems passing a bind function with no arguments into one expecting an argument double works fine? If I were to write out the bind function explicitly, what should that be?
struct MyClass
{
void f()
{
std::cout << "f()" << std::endl;
}
};
void bar( const boost::function<void(const double&)>& f )
{
f( 1.0 );
}
int main()
{
MyClass c;
// why this compiles
bar( boost::bind( &MyClass::f, &c ) );
// what should I write if I want to create the binded function explicitly before pass into bar?
// boost::function<void(const double&)> f = boost::bind( ... boost::bind( &MyClass::f, &c ), ?? )
bar( f );
}
Upvotes: 1
Views: 3112
Reputation: 392833
This is by design, unbound parameters (e.g. 1.0
) passed when invoking the bind-expression are just ignored.
boost::function<void(const double&)> f = boost::bind(&MyClass::f, &c);
bar(f);
would do nicely for explicit assignment of the bind expression.
Update to the comment:
Remember, two guidelines:
function<...>
has a fixed signaturebind
expressions do not have a fixed signature. The whole purpose of bind
is to change the signature. This includes e.g.
So while you cannot assign different func<...>
types to eachother, you can always bind
the one signature to the other.
Here's a more complete demonstration that shows the limits of what you can do with function
and bind
, and why (how it behaves): Live On Coliru:
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <iostream>
#include <cassert>
int foo0() { return 0; }
int foo1(int) { return 1; }
int foo2(int,int) { return 2; }
int foo3(int,int,int) { return 3; }
int main()
{
boost::function<int()> func0;
boost::function<int(int)> func1;
boost::function<int(int,int)> func2;
boost::function<int(int,int,int)> func3;
// "straight" assignment ok:
// -------------------------
func0 = foo0; assert (0 == func0());
func1 = foo1; assert (1 == func1(-1));
func2 = foo2; assert (2 == func2(-1,-1));
func3 = foo3; assert (3 == func3(-1,-1,-1));
// "mixed" assignment not ok:
// --------------------------
// func0 = foo1; // compile error
// func3 = foo2; // compile error
// func1 = func2; // compile error, just the same
// func2 = func1; // compile error, just the same
// SOLUTION: you can always rebind:
// --------------------------------
func0 = boost::bind(foo3, 1, 2, 3); assert (func0() == 3);
func3 = boost::bind(foo1, _3); assert (func3(-1,-1,-1) == 1);
func3 = boost::bind(foo2, _3, _2); assert (func3(-1,-1,-1) == 2);
// same arity, reversed arguments:
func3 = boost::bind(foo3, _3, _2, _1); assert (func3(-1,-1,-1) == 3);
// can't bind more than number of formal parameters in signature:
// --------------------------------------------------------------
// func3 = boost::bind(foo1, _4); // in fact, the bind is fine, but assigning to `func3` fails
}
All asserts pass. You can try what the compiler says when you uncomment the lines that don't compile.
Cheers
Upvotes: 2