代码之家  ›  专栏  ›  技术社区  ›  cjds

std::bind未绑定到typedef

  •  0
  • cjds  · 技术社区  · 6 年前

    std::bind 有一个图书馆 typedef

    #include <iostream>
    #include <string>
    #include <functional>
    
    typedef void (*GDBusReturnFunction) (void* user_data);
    
    class Test
    {
       void reply(void* user_data)
       {
          std::cout << "Hello" << std::endl;
          return;
       }
    
       void test_reply()
       {
          auto reply_func = std::bind(&Test::reply, this, std::placeholders::_1);
          call(reply_func);
       }
    
       void call(GDBusReturnFunction func)
       {}
    };
    
    int main()
    {
       Test();
    }
    
    

    这就是我得到的编译错误

    prog.cc:19:11: error: cannot convert 'std::_Bind<void (Test::*(Test*, std::_Placeholder<1>))(void*)>' to 'GDBusReturnFunction' {aka 'void (*)(void*)'}
       19 |      call(reply_func);
          |           ^~~~~~~~~~
          |           |
          |           std::_Bind<void (Test::*(Test*, std::_Placeholder<1>))(void*)>
    prog.cc:22:33: note:   initializing argument 1 of 'void Test::call(GDBusReturnFunction)'
       22 |   void call(GDBusReturnFunction func)
          |             ~~~~~~~~~~~~~~~~~~~~^~~~
    

    static 不要使用 绑定 事情按预期进行。


    我也试过这个

         call(&reply_func);
    

    但这会返回相同的错误

    1 回复  |  直到 6 年前
        1
  •  1
  •   JeJo    6 年前

    这个 std::bind 返回一个 未指明 类型(即未指定类型的函数对象),

    template< class F, class... Args >
    /*unspecified*/ bind( F&& f, Args&&... args );
    //^^^^^^^^^^^^
    

    尽管如此 可以替换为 lambda function

    [this](auto user_data) { this->reply(user_data); }
    

    使用模板的示例解决方案 Test::call 函数,可能看起来像。 See a demo

    #include <iostream>
    #include <string>
    
    class Test
    {
    public:
       // optionally you could make it also template function!
       // e.g.
       // template<typename Type>
       // void reply(Type* user_data)
       void reply(void* user_data)
       {
          std::cout << "Hello" << std::endl;
       }
    
       void test_reply()
       {
          call([this](auto user_data) { this->reply(user_data); });
       }
    
       template<typename Callable>
       void call(Callable func) const
       {
          int userData = 1; // some user data
          func(&userData);
       }
    };