C++的占位符std::placeholder

版权声明:所有的博客都是个人笔记,交流可以留言。未经允许,谢绝转载。。。 https://blog.csdn.net/qq_35976351/article/details/90146211

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

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

#include <functional>
#include <string>
#include <iostream>

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

猜你喜欢

转载自blog.csdn.net/qq_35976351/article/details/90146211
今日推荐