C++使用std::bind結合使用進行回調.

  • 參數

    參數類型不應該是具體類型,而是std::function類型.

  • 代碼

    #include<string>
    #include<iostream>
    #include<functional>
    
    using ExampleFunction = std::function<void(const char*)>;
    
    class Object {
    public:
       void hello(const std::string& s)
       {
           std::cout << "Hello " << s << '\n';
       }
       void hello(const char*s)
       {
           std::cout << "Hello " << s << '\n';
       }
       void call(ExampleFunction func)
       {
           func("in call");
       }
    };
    
    int main()
    {
       Object instance;
       std::string str("World");
       ExampleFunction f = std::bind((void(Object::*)(const char*))&Object::hello, &instance, 
                                     std::placeholders::_1);
       f("hello");
       instance.call(f);
    }
    
  • 發表評論
    所有評論
    還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
    相關文章