Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use std::bind with overloaded functions

I cannot find out how to bind a parameter to an overloaded function using std::bind. Somehow std::bind cannot deduce the overloaded type (for its template parameters). If I do not overload the function everything works. Code below:

#include <iostream>
#include <functional>
#include <cmath>

using namespace std;
using namespace std::placeholders;

double f(double x) 
{
    return x;
}

// std::bind works if this overloaded is commented out
float f(float x) 
{
    return x;
}

// want to bind to `f(2)`, for the double(double) version

int main()
{

    // none of the lines below compile:

    // auto f_binder = std::bind(f, static_cast<double>(2));

    // auto f_binder = bind((std::function<double(double)>)f, \
    //  static_cast<double>(2));

    // auto f_binder = bind<std::function<double(double)>>(f, \
    //  static_cast<double>(2));

    // auto f_binder = bind<std::function<double(double)>>\
    // ((std::function<double(double)>)f,\
    //  static_cast<double>(2));

    // cout << f_binder() << endl; // should output 2
}

My understanding is that std::bind cannot deduce somehow its template parameters, since f is overloaded, but I cannot figure out how to specify them. I tried 4 possible ways in the code (commented lines), none works. How can I specify the type of function for std::bind? Any help is much appreciated!

like image 831
vsoftco Avatar asked Jul 21 '14 20:07

vsoftco


People also ask

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 .

How are function calls matched with overloaded functions?

The call is resolved for an overloaded subroutine by an instance of function through a process called Argument Matching also termed as the process of disambiguation.

What are the restrictions on overloaded function?

Restrictions on overloadingAny two functions in a set of overloaded functions must have different argument lists. Overloading functions that have argument lists of the same types, based on return type alone, is an error.

What is the use of bind function 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.


1 Answers

You may use:

auto f_binder = std::bind(static_cast<double(&)(double)>(f), 2.);

or

auto f_binder = bind<double(double)>(f, 2.);

Alternatively, lambda can be used:

auto f_binder = []() {
    return f(2.);     // overload `double f(double)` is chosen as 2. is a double.

};
like image 52
Jarod42 Avatar answered Sep 19 '22 07:09

Jarod42