问题 std :: bind和重载函数


请参阅以下代码段。我想用 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;
}

5987
2017-10-25 08:37


起源

你错过了一个 return 在你的lambda。 - ildjarn


答案:


你需要使用 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); };

13
2017-10-25 08:46



感谢ecatmur,它的工作原理。 - Atul
并且可以使用按值捕获 [&,i] 要么 [=,&cl]。 - Xeo