Was wondering if its possible to use parameters in my functions (may be different amount of parameters in each of the functions) |
Yes this is possible, though I would question your design if differing parameters is really necessary.
There are 2 function signatures with std::function:
1) The signature of the function being called (ie: what you have a pointer to)
2) The signature of the std::function itself (ie: how you call it)
std::bind ties the two together.
In my previous example:
1 2 3 4 5 6
|
std::function<void()> f; // <- void() is std::function's signature
// meaning this function can be called with no parameters and returns void
// however... Ball::anotherFunction takes a hidden 'this' parameter, so it doesn't
// quite match that signature. Therefore we need to use bind:
f = std::bind( &Ball::anotherFunction, this );
|
The first parameter to bind is the pointer to the function we're calling... and then the parameters after it are the params passed to that function. The first of which is the hidden 'this' parameter (if the object is a member function).
In your case, you want to change std::function's signature to void(int) so you can pass a single int as a parameter:
1 2 3 4 5
|
std::function<void(int)> f;
f = std::bind( &Ball::move, this, std::placeholders::_1 );
f(5); // calls this->move(5);
|
Here, bind passes 'this' as the hidden 'this' param for the function... and it
uses a 'placeholder' meaning "whatever you pass to the std::function when you call it". Since we call
f(5);
, 5 is used as placeholders::_1, which is passed as the next parameter to Ball::move.
If the function has a different signature, you just have to fill in the params as necessary when you bind it.
1 2 3 4 5 6 7 8 9 10 11 12
|
void Ball::Move2(int x, int y) { ... }
std::function<void(int)> f;
f = std::bind( &Ball::Move2, this, std::placeholders::_1, 0 );
f(3); // calls this->Move2( 3, 0 );
f = std::bind( &Ball::Move2, this, 5, std::placeholders::_1 );
f(2); // calls this->Move2( 5, 2 );
//etc
|