I've been reading up on boost::function
and boost::bind
, however, I can't seem to figure out a "good way" to call a boost
function if all the arguments are bound (I think that's the right terminology). Below is an untested MCVE (copying-and-pasting my real code is not ideal).
#include "boost/function.hpp"
#include "boost/bind.hpp"
#include <iostream>
void func(void* args)
{
int* myInt = static_cast<int*>(args);
if (myInt != NULL)
{
std::cout << "myInt = " << *myInt << std::endl;
}
else
{
std::cout << "args is NULL" << std::endl;
}
}
int main()
{
int myInt1 = 5;
int myInt2 = 45;
boost::function<void(void* args)> myFunc = boost::bind(&func, &myInt1);
// here's my problem,, how do I call myFunc?
myFunc(); // this does not compile due to missing arguments
myFunc; // this is essentially a no-op. The function doesn't execute,
// and if I put a breakpoint here, it either goes to the next
// line or I get a warning that no executable code exists here
// after some experimentation, I realized I can do this and it works
myFunc(NULL); // this prints out "myInt = 5"
// this also prints out "myInt = 5"
boost::bind(&func, &myInt1)();
// finally, this prints out "myInt = 5" as well
myFunc(&myInt2);
return 0;
}
So my question is, what's the preferred/right way to call myFunc
? I've successfully called functions with the _1
, _2
, etc argument placeholders by passing in the appropriate arguments.. maybe in practice there are placeholders almost all the time? myFunc(NULL)
works, but it seems silly to me that I must essentially make up arguments if I've already bound them (and what I pass in doesn't matter anyway). In my real code, I actually want to call myFunc
in a different function (so boost::bind(&func, &myInt1)();
isn't an option), and I'm doing so inside an object of a class, so I hope the example I've provided exhibits identical behavior to what I'm seeing in my real code. I'm using Visual Studio 2013, and c++11 or later cannot be used.
myFunc
is wrong, it should beboost::function<void()> myFunc
, then justmyFunc()
.auto myFunc
.auto myFunc
for C++03