std :: bind和重载函数 [英] std::bind and overloaded function

查看:145
本文介绍了std :: bind和重载函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参考以下代码段。我想使用 std :: bind 来重载函数 foobar 。它只调用没有参数的方法。

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


推荐答案

c $ c>占位符用于未绑定的参数:

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

您还可以使用lambda捕获执行绑定(注意,这是绑定 cl c>

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

这篇关于std :: bind和重载函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆