1

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);
}
Soumyajit Roy
  • 463
  • 2
  • 8
  • 17
  • `_1` is in the `std::placeholders` namespace not the global namespace – Alan Birtles Oct 03 '20 at 06:46
  • I am still trying to figure out why you want to use one technique that's inferior to an other ,lamdas are not about personal style it is just something that is suggested and in a lot of cases it is faster that bind [lamda vs bind](https://stackoverflow.com/questions/24852764/stdbind-vs-lambda-performance) – Spyros Mourelatos Oct 03 '20 at 06:54
  • I know. Actually this function is a legacy function so I thought of just binding it to the callback. – Soumyajit Roy Oct 03 '20 at 06:56

2 Answers2

2

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);
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
1

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

273K
  • 29,503
  • 10
  • 41
  • 64