1

我想让这段代码正常工作,我该怎么办?

在最后一行给出这个错误。

我究竟做错了什么?我知道 boost::bind 需要一个类型,但我没有。帮助

class A
{

public:

    template <class Handle>
    void bindA(Handle h)
    {
        h(1, 2);
    }
};

class B
{

    public:
        void bindB(int number, int number2)
        {
            std::cout << "1 " << number << "2 " << number2 << std::endl;
        }
};


template < class Han > struct Wrap_
{

    Wrap_(Han h) : h_(h) {}

    template<typename Arg1, typename Arg2> void operator()(Arg1 arg1, Arg2 arg2)
    {
        h_(arg1, arg2);
    }
    Han h_;
};

template< class Handler >

    inline Wrap_<Handler> make(Handler h)
    {
        return Wrap_<Handler> (h);
    }
int main()
{

    A a;
    B b;
    ((boost::bind)(&B::bindB, b, _1, _2))(1, 2);
    ((boost::bind)(&A::bindA, a, make(boost::bind(&B::bindB, b, _1, _2))))();
/*i want compiled success and execute success this code*/

}
4

1 回答 1

2

您遇到的问题是您正在尝试绑定到模板化函数。在这种情况下,您需要指定要调用绑定的方法的模板类型。

该方法正在发生这种情况A::bindA。有关使用提供的类正确编译的 main 的代码片段,请参见下文。

顺便说一下,在示例中,我使用boost::function(要绑定的姊妹库)来指定正在使用的函数指针类型。我认为这使它更具可读性,如果您要继续使用 bind,强烈建议您熟悉它。

#include "boost/bind.hpp"
#include "boost/function.hpp"

int main(int c, char** argv)
{
  A a;
  B b;

  typedef boost::function<void(int, int)> BFunc;
  typedef boost::function<void(BFunc)> AFunc;
  BFunc bFunc( boost::bind(&B::bindB, b, _1, _2) );
  AFunc aFunc( boost::bind(&A::bindA<BFunc>, a, make(bFunc)) );

  bFunc(1,2);
}
于 2010-06-01T04:18:47.390 回答