10

我不知道如何使用 . 将参数绑定到重载函数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
}

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

4

1 回答 1

17

您可以使用:

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

或者

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

或者,可以使用 lambda:

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

};
于 2014-07-21T20:53:17.497 回答