简体   繁体   English

std :: bind和重载函数

[英]std::bind and overloaded function

Please refer the following code snippet. 请参阅以下代码段。 I want to use the std::bind for overloaded function foobar . 我想使用std::bind来重载函数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;
}

You need to use placeholders for the unbound arguments: 您需要为未绑定的参数使用placeholders

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): 您还可以使用lambda捕获执行绑定(请注意,这是通过引用绑定cl ,而不是通过值绑定):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 std :: bind函数中没有可行的重载&#39;=&#39; - No viable overloaded '=' in std::bind function std :: bind与父类的重载函数 - std::bind with overloaded function from parent class 如何在std :: bind中指示给定签名的重载函数? - How to indicate the overloaded function of given signature in std::bind? 将 std::bind 与重载函数一起使用 - use std::bind with overloaded functions 重载std :: bind占位符的运算符 - Overloaded operators for std::bind placeholders 如何解决错误:“没有匹配的函数来调用&#39;bind( <unresolved overloaded function type> 在类中使用std :: bind时 - How to solve the error: “no matching function for call to ‘bind(<unresolved overloaded function type>” when std::bind is used in a class boost :: bind,std :: bind和重载函数 - boost::bind, std::bind and overloaded functions std :: bind到std :: function? - std::bind to std::function? 没有匹配的函数来调用&#39;bind( <unresolved overloaded function type> ,const std :: _ Placeholder &lt;1&gt;&,int *) - no matching function for call to ‘bind(<unresolved overloaded function type>, const std::_Placeholder<1>&, int*) std :: bind()错误:无法确定重载函数的哪个实例“boost :: asio :: io_service :: run”是打算 - std::bind() error: cannot determine which instance of overloaded function “boost::asio::io_service::run” is intended
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM