如何将 stl 队列推送功能绑定到 std::function?

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

我试过了

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

但它不起作用

对于queue<int>push的参数类型应该是const int&int&&,所以你应该改变static_cast来匹配类型。

例如来自

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

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

LIVE

更简单的方法是使用 lambda 函数

{
    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 
}