std::bind and overloaded function

…衆ロ難τιáo~ 提交于 2019-12-05 17:54:48

问题


Please refer the following code snippet. I want to use the std::bind for overloaded function foobar. It calls only the method with no arguments.

#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;
}

回答1:


You need to use placeholders for the unbound arguments:

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

You can also perform the binding with a lambda capture (note that this is binds cl by reference, not by value):

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


来源:https://stackoverflow.com/questions/13064698/stdbind-and-overloaded-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!