指向功能的指针

Max*_*rai 2 c++ pointers boost-bind boost-function

我必须将函数传递给指针.为此我正在使用boost :: function.对于不同的签名,捕获指针的函数被重载.例如:

void Foo(boost::function<int ()>) { ... }
void Foo(boost::function<float ()>) { ... }
void Foo(boost::function<double ()>) { ... }
Run Code Online (Sandbox Code Playgroud)

现在我想在那里传递一些类方法指针:

class test
{
   public:
      float toCall() { };
};

class Wrapper
{
  Wrapper() {
    test obj;
    Foo(boost::bind(&test::toCall, this));
  }
};


error: no matching function for call to ‘Foo(boost::_bi::bind_t<float, boost::_mfi::mf0<float, test>, boost::_bi::list1<boost::_bi::value<Wrapper*> > >)’
    note: candidates are: Foo(boost::function<float()>&)
Run Code Online (Sandbox Code Playgroud)

Joh*_*itb 6

Nonono这不起作用.因为boost::function<...>有一个模板化的构造函数来接受任何和所有类型.稍后将检查与呼叫签名的兼容性.重载解决方案无法解决此问题.

此外,我认为你想通过&obj而不是this.尝试明确转换:

Foo(boost::function<float ()>(boost::bind(&test::toCall, &obj)));
Run Code Online (Sandbox Code Playgroud)

这非常难看,所以你可能想引入一个typedef

void Foo(FloatHandler) { ... }
...
FloatHandler f(boost::bind(&test::toCall, &obj));
Foo(f);
Run Code Online (Sandbox Code Playgroud)

或者最终你可以创建Foo一个只接受任何可调用类型的模板T.我怀疑这可能是最简单的,因为在一般情况下我怀疑你不知道boost::function<...>你需要投什么.那些想要回归的人怎么样std::complex<>?所以...

template<typename T>
void Foo(T) { ... }
...
Foo(boost::bind(&test::toCall, &obj));
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.