将std :: bind与重载函数一起使用

vso*_*tco 7 c++ overloading stdbind c++11

我无法找到如何使用参数将参数绑定到重载函数std::bind.不知何故std::bind不能推断出重载类型(对于它的模板参数).如果我不重载该功能一切正常.代码如下:

#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
}
Run Code Online (Sandbox Code Playgroud)

我的理解是,std::bind不能以某种方式推断出它的模板参数,因为它f是重载的,但我无法弄清楚如何指定它们.我在代码中尝试了4种可能的方式(注释行),没有效果.如何指定函数类型std::bind?任何帮助深表感谢!

Jar*_*d42 13

你可以使用:

auto f_binder = std::bind(static_cast<double(&)(double)>(f), 2.);
Run Code Online (Sandbox Code Playgroud)

要么

auto f_binder = bind<double(double)>(f, 2.);
Run Code Online (Sandbox Code Playgroud)

或者,可以使用lambda:

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

};
Run Code Online (Sandbox Code Playgroud)