Use std :: bind with overloaded functions

I cannot learn how to bind a parameter to an overloaded function using std::bind . Somehow, std::bind cannot output an 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 } 

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

+6
source share
1 answer

You can use:

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

or

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

Alternatively, you can use lambda:

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

Source: https://habr.com/ru/post/972616/


All Articles