Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::bind and overloaded function

Tags:

c++

c++11

stdbind

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;
}
like image 270
Atul Avatar asked Oct 25 '12 08:10

Atul


People also ask

What is the use of std :: bind?

std::bind is a Standard Function Objects that acts as a Functional Adaptor i.e. it takes a function as input and returns a new function Object as an output with with one or more of the arguments of passed function bound or rearranged.

How does bind work in C++?

Bind function with the help of placeholders helps to manipulate the position and number of values to be used by the function and modifies the function according to the desired output. What are placeholders? Placeholders are namespaces that direct the position of a value in a function.

What is the return type of std :: bind?

std::bind return type The return type of std::bind holds a member object of type std::decay<F>::type constructed from std::forward<F>(f), and one object per each of args... , of type std::decay<Arg_i>::type, similarly constructed from std::forward<Arg_i>(arg_i).

How are function calls matched with overloaded functions?

The compiler selects which overloaded function to invoke based on the best match among the function declarations in the current scope to the arguments supplied in the function call. If a suitable function is found, that function is called. "Suitable" in this context means either: An exact match was found.


1 Answers

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); };
like image 126
ecatmur Avatar answered Oct 17 '22 23:10

ecatmur