我去过 reading up在 boost::function
和 boost::bind
上,但是,我似乎无法找到调用 boost
的“好方法” > 如果所有参数都已绑定(bind)则函数(我认为这是正确的术语)。下面是一个未经测试的 MCVE(复制粘贴我的真实代码并不理想)。
#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;
}
所以我的问题是,调用 myFunc
的首选/正确方法是什么?我已经通过传入适当的参数成功地调用了带有 _1
、_2
等参数占位符的函数。也许在实践中几乎所有时间都有占位符? myFunc(NULL)
有效,但对我来说这似乎很愚蠢,如果我已经绑定(bind)了参数(并且我传入的内容无论如何都无关紧要),我必须基本上组成参数。在我的真实代码中,我实际上想在不同的函数中调用 myFunc
(所以 boost::bind(&func, &myInt1)();
不是一个选项),我在一个类的对象中这样做,所以我希望我提供的示例表现出与我在真实代码中看到的相同的行为。我正在使用 Visual Studio 2013,无法使用 c++11 或更高版本。
最佳答案
“绑定(bind)所有参数”的函数对象没有参数,所以它的类型是 boost::function<void()>
.你需要
boost::function<void()> myFunc = boost::bind(&func, &myInt1);
关于c++ - 如何调用绑定(bind)了所有参数的 boost::function 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54680798/