【问题标题】:how to bind stl queue push function to a std::function?如何将 stl 队列推送函数绑定到 std::function?
【发布时间】:2020-06-03 10:44:14
【问题描述】:

我试过了

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

但它不起作用

【问题讨论】:

  • 改用 lambda 表达式。

标签: c++ queue bind std-function


【解决方案1】:

更简单的方法是使用 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 
}

【讨论】:

    【解决方案2】:

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

    例如来自

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

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

    LIVE

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-22
      • 1970-01-01
      • 1970-01-01
      • 2012-07-07
      • 1970-01-01
      • 1970-01-01
      • 2013-12-14
      相关资源
      最近更新 更多