简体   繁体   中英

Use std::bind and store into a std:: function

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);
}

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM