how to bind stl queue push function to a std::function?

Viewed 187

I tried this

{
    std::function<void(int)> push;
    queue<int> myqueue; 
    push = std::bind(static_cast<void (queue<int>::*)(int)>(&queue<int>::push), &myqueue,std::placeholders::_1);
    push(8);
}

but it is not working

2 Answers

The easier way to do it, is using a lambda function

{
    queue<int> myqueue;
    auto push = [&myqueue](int param) { myqueue.push(param); }; 
    push(8); // myqueue - should be still reachable as it's captured by reference into a lambda capture lust 
}

For queue<int>, push's parameter type is supposed to be const int& or int&&, so you should change the static_cast to match the type.

E.g. from

static_cast<void (queue<int>::*)(int)>(&queue<int>::push)

to

static_cast<void (queue<int>::*)(const int&)>(&queue<int>::push)

LIVE

Related