C++的占位符std::placeholder

笔记参考自官方文档: https://en.cppreference.com/w/cpp/utility/functional/placeholders

简单一句话概括, 一个变量的占位符, 用于函数绑定时使用, 具体直接参考代码:

#include 
#include 
#include 

void goodbye(const std::string& s) {
    std::cout << "Goodbye " << s << '\n';
}

class Object {
  public:
    void hello(const std::string& s) {
        std::cout << "Hello " << s << '\n';
    }
};

int main() {
    typedef std::function<void(const std::string&)> ExampleFunction;
    Object instance;
    std::string str("World");
    ExampleFunction f = std::bind(&Object::hello, &instance,
                                  std::placeholders::_1);

    // equivalent to instance.hello(str)
    f(str);
    f = std::bind(&goodbye, std::placeholders::_1);

    // equivalent to goodbye(str)
    f(str);
    return 0;
}

输出:

Hello World
Goodbye World

你可能感兴趣的:(C++笔记)