如何调用绑定所有参数的 boost::function 对象

yan*_*ano 2 c++ boost c++03

我一直在阅读and boost::function,但是,如果所有参数都被绑定,boost::bind我似乎无法找出调用函数的“好方法” (我认为这是正确的术语)。boost下面是未经测试的 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;
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是,首选/正确的通话方式是什么myFunc?我已经通过传入适当的参数成功地使用_1_2等参数占位符调用函数。也许在实践中几乎总是有占位符?myFunc(NULL)有效,但对我来说,如果我已经绑定了它们,我必须本质上编造论点,这似乎很愚蠢(而且我传递的内容无论如何并不重要)。在我的真实代码中,我实际上想调用myFunc不同的函数(所以boost::bind(&func, &myInt1)();不是一个选项),并且我是在类的对象内这样做的,所以我希望我提供的示例表现出与我在我的真实代码中看到了。我使用的是 Visual Studio 2013,无法使用 c++11 或更高版本。

jua*_*nza 5

具有“所有参数绑定”的函数对象没有参数,因此其类型为boost::function<void()>. 你需要

boost::function<void()> myFunc = boost::bind(&func, &myInt1);
Run Code Online (Sandbox Code Playgroud)