我不知道如何使用 . 将参数绑定到重载函数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
?任何帮助深表感谢!