Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::bind overload resolution

The following code works fine

#include <functional>

using namespace std;
using namespace std::placeholders;

class A
{
  int operator()( int i, int j ) { return i - j; }
};

A a;
auto aBind = bind( &A::operator(), ref(a), _2, _1 );

This does not

#include <functional>

using namespace std;
using namespace std::placeholders;

class A
{
  int operator()( int i, int j ) { return i - j; }
  int operator()( int i ) { return -i; }
};

A a;
auto aBind = bind( &A::operator(), ref(a), _2, _1 );

I have tried playing around with the syntax to try and explicitly resolve which function I want in the code that does not work without luck so far. How do I write the bind line in order to choose the call that takes the two integer arguments?

like image 416
bpw1621 Avatar asked Nov 11 '10 21:11

bpw1621


People also ask

What is overload resolution?

The process of selecting the most appropriate overloaded function or operator is called overload resolution. Suppose that f is an overloaded function name. When you call the overloaded function f() , the compiler creates a set of candidate functions.

What is the use of std :: bind?

std::bind. The function template bind generates a forwarding call wrapper for f . Calling this wrapper is equivalent to invoking f with some of its arguments bound to args .

What is function overloading C++?

Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading.

What is c++ bind?

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.


2 Answers

You need a cast to disambiguate the overloaded function:

(int(A::*)(int,int))&A::operator()
like image 79
James McNellis Avatar answered Oct 05 '22 01:10

James McNellis


If you have C++11 available you should prefer lambdas over std::bind since it usually results in code that is more readable:

auto aBind = [&a](int i, int j){ return a(i, j); };

compared to

auto aBind = std::bind(static_cast<int(A::*)(int,int)>(&A::operator()), std::ref(a), std::placeholders::_2, std::placeholders::_1);
like image 27
sigy Avatar answered Oct 05 '22 01:10

sigy