C++ 如何生成一个模板函数,该函数采用boost::bind的结果参数?

C++ 如何生成一个模板函数,该函数采用boost::bind的结果参数?,c++,boost,boost-bind,C++,Boost,Boost Bind,我有一个helper方法,它将一个boost::function类型对象作为输入,并用另一个处理其他逻辑的functor包装该函数 以下是我的签名: class Example { public: typedef ... Callback; ... template<typename T> static Callback make_wrapper( const boost::function<void( T )>& ); };

我有一个helper方法,它将一个
boost::function
类型对象作为输入,并用另一个处理其他逻辑的functor包装该函数

以下是我的签名:

class Example {
public:
    typedef ... Callback;

    ...

    template<typename T>
    static Callback make_wrapper( const boost::function<void( T )>& );
};
这使得:

error: no matching function for call to 'make_wrapper'
note: candidate template ignored: could not match 'function' against 'bind_t'
我找到了两种解决方法:

  • 温度变量:

    boost::function<void( uint32_t )> f = boost::bind( &OtherClass::method, other, _1 );
    Example::Callback c = Example::make_wrapper ( f );
    
    boost::function f=boost::bind(&OtherClass::method,other,_1);
    示例::回调c=示例::生成包装器(f);
    
  • 调用make_包装的特定专门化:

    Example::Callback c = Example::make_wrapper<uint32_t> ( boost::bind( &OtherClass::method, other, _1 ) );
    
    Example::Callback c=Example::make_包装(boost::bind(&OtherClass::method,other,_1));
    
  • 如果我能跳过额外的提示,用内联调用bind调用make_包装器,我会更喜欢它


    是否有一种方法可以声明make_包装模板的签名,以帮助编译器在不使用上述解决方法的情况下确定类型?

    两者都可以,并将返回类型列为未指定。这意味着您根本无法知道这一点,如果您想要完全可移植。

    每当您使用
    bind
    时,您都会放弃有关绑定函数参数类型的所有信息。函数模板不可能推断参数类型
    t
    ,因为
    bind
    的返回值是一个函数对象,可以使用任意类型的任意数量的参数调用

    您可以将
    bind
    函数包装到helper函数模板中,以推断绑定成员函数,尤其是其结果类型和参数(示例使用
    std::bind
    std::function
    ,但我相信它可以很容易地转换为
    boost
    ):

    #包括
    #包括
    #包括
    结构foo{
    空栏(int a,std::string s){
    
    std::不能使用
    auto
    decltype
    Example::Callback c = Example::make_wrapper<uint32_t> ( boost::bind( &OtherClass::method, other, _1 ) );
    
    #include <iostream>
    #include <string>
    #include <functional>
    
    struct foo {
      void bar(int a, std::string s) {
         std::cout << a << " " << s << std::endl;
      }
    };
    
    
    template<typename T1, typename T2>
    void make_wrapper(const std::function<void( T1, T2 )>&) {
    }
    
    template <class Foo, class Res, class... Args, class... Placeholders>
    std::function<Res(Args...)> my_bind(Res (Foo::*bar)(Args...), Foo& f, Placeholders... ps) {
       return std::bind(bar, f, ps...);
    }
    
    int main() {
      foo f;
      make_wrapper(my_bind(&foo::bar, f, std::placeholders::_1, std::placeholders::_2));
    }