【问题标题】:std::bind and overloaded functionstd::bind 和重载函数
【发布时间】:2012-10-15 09:46:08
【问题描述】:

请参考以下代码sn-p。我想将std::bind 用于重载函数foobar。它只调用不带参数的方法。

#include <functional>
#include <iostream>
class Client
{  
  public :  
  void foobar(){std::cout << "no argument" << std::endl;}
  void foobar(int){std::cout << "int argument" << std::endl;}
  void foobar(double){std::cout << "double argument" << std::endl;}
};

int main()
{
    Client cl;  
    //! This works 
    auto a1 = std::bind(static_cast<void(Client::*)(void)>(&Client::foobar),cl);
    a1();
    //! This does not
    auto a2= [&](int)
    {
        std::bind(static_cast<void(Client::*)(int)>(&Client::foobar),cl);
    };
    a2(5);
    return 0;
}

【问题讨论】:

  • 您在 lambda 中缺少 return

标签: c++ c++11 stdbind


【解决方案1】:

对于未绑定的参数,您需要使用placeholders

auto a2 = std::bind(static_cast<void(Client::*)(int)>(&Client::foobar), cl,
                    std::placeholders::_1);
a2(5);

您还可以使用 lambda 捕获执行绑定(请注意,这是通过引用绑定 cl,而不是通过值):

auto a2 = [&](int i) { cl.foobar(i); };

【讨论】:

  • 可以使用[&amp;,i][=,&amp;cl]进行按值捕获。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-28
  • 1970-01-01
  • 2014-09-12
  • 1970-01-01
  • 2016-04-26
  • 2011-05-08
  • 1970-01-01
相关资源
最近更新 更多