Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
733 views
in Technique[技术] by (71.8m points)

c++ - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...