本文共 680 字,大约阅读时间需要 2 分钟。
std::function + std::bind使得所有函数能够统一到
std::function。在实际应用中,这种统一方式可以让类成员函数以一种优雅的方式被用在回调、线程函数等多个场景中。 以下是一个示例代码:#include #include using std::placeholders::_1;using std::placeholders::_2;class Test{ public: int add(const int a, const int b) { return a + b; }}//int main(){ Test t; std::function< int(int, int) > pfun = std::bind(&Test::add, &t, _1, _2); //auto pfun = std::bind(&Test::add, &t, _1, _2); // 直接调用 pfun(2, 3); // 用于线程函数 std::thread t(pfun, 4, 6); return 0;}通过糖霜&std::bind,我们可以将类成员函数统一到标准的 std::function类型中,这使得函数能够方便地被用在多种场景中。 在实际应用中,std::function和std::bind提供了一种强大的方式来处理函数编织和灵活配置,这在诸如回调处理、线程函数执行等场景中尤为重要。
转载地址:http://ftyaz.baihongyu.com/