【C++】 bind examples

发布时间 2023-09-05 11:32:08作者: dilex

Simple Example

#include <algorithm>
#include <vector>
#include <iostream>

void print(std::string prefix, int number)
{
    std::cout << prefix << " - " << number << std::endl;
}

int main(int argc, char* argv[])
{
    std::vector<int> numbers;
    for (int i = 0; i < 100; ++i)
    {
        numbers.push_back(i);
    }
    std::for_each(numbers.begin(), numbers.end(), std::bind(print, "main()", std::placeholders::_1));
    return 0;
}

Bind to Class Member function

#include <algorithm>
#include <vector>
#include <iostream>

class Test{
public:
    Test(){
        age = 100;
    }
    void print(int task_id){
        std::cout << task_id << " - " << age << std::endl;
    }
private:
    int age;
};

int main(int argc, char* argv[])
{
    std::vector<int> numbers = {1, 2, 3};
    Test test;
    std::for_each(numbers.begin(), numbers.end(), std::bind(&Test::print, &test, std::placeholders::_1));
    return 0;
}