【发布时间】:2020-10-03 06:42:14
【问题描述】:
我正在尝试使用 std::bind 绑定到函数并将其存储到我的 std::function 回调对象中。我写的代码是我实际代码的简化版本。下面的代码不能编译,说
_1 未在范围内声明
注意:我知道使用 lambda 也可以做到这一点。但是函数处理程序已经存在并且需要使用,否则我需要在 lambda 中调用处理程序。
#include <iostream>
#include <functional>
typedef std:: function<void(int)> Callback;
template <class T>
class Add
{
public:
Add(Callback c)
{
callback = c;
}
void add(T a, T b)
{
callback(a+b);
}
private:
Callback callback;
};
void handler(int res)
{
printf("result = %d\n", res);
}
int main(void)
{
// create a callback
// I know it can be done using lambda
// but I want to use bind to handler here
Callback c = std::bind(handler, _1);
/*Callback c = [](int res)
{
printf("res = %d\n", res);
};*/
// create template object with
// the callback object
Add<int> a(c);
a.add(10,20);
}
【问题讨论】:
-
_1位于std::placeholders命名空间而非全局命名空间中 -
我仍在试图弄清楚为什么你要使用一种不如另一种的技术,lamdas 与个人风格无关,它只是建议的东西,在很多情况下它更快绑定lamda vs bind
-
我知道。实际上这个函数是一个遗留函数,所以我想只是将它绑定到回调。
标签: c++ std-function stdbind