Reputation: 463
I am trying to use std::bind to bind to a function and store it into my std::function callback object. The code I wrote is the simplified version of my actual code. The below code does not compile, says
_1 was not declared in the scope
Note: I know the same can be done using a lambda. However the function handler is already present and need to be used else I need to call the handler inside the 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);
}
Upvotes: 1
Views: 629
Reputation: 172924
The placeholders _1
, _2
, _3
... are placed in namespace std::placeholders
, you should qualify it like
Callback c = std::bind(handler, std::placeholders::_1);
Or
using namespace std::placeholders;
Callback c = std::bind(handler, _1);
Upvotes: 2
Reputation: 38508
Placeholders are in own namespace in the std namespace.
Add using namespace std::placeholders
or use std::placeholders::_1
Good examples: std::placeholders::_1, std::placeholders::_2, ..., std::placeholders::_N
Upvotes: 1