使用std :: bind与重载函数 [英] use std::bind with overloaded functions
问题描述
我找不到使用std::bind
将参数绑定到重载函数的方法. std::bind
不能以某种方式推断出重载类型(用于其模板参数).如果我不重载该功能,则一切正常.下面的代码:
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
}
我的理解是,由于f
被重载,std::bind
无法以某种方式推断出其模板参数,但是我无法弄清楚如何指定它们.我在代码中尝试了4种可能的方式(注释行),但均无效果.如何指定std::bind
的函数类型?任何帮助深表感谢!
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!
推荐答案
您可以使用:
auto f_binder = std::bind(static_cast<double(&)(double)>(f), 2.);
或
auto f_binder = bind<double(double)>(f, 2.);
或者,可以使用lambda:
Alternatively, lambda can be used:
auto f_binder = []() {
return f(2.); // overload `double f(double)` is chosen as 2. is a double.
};
这篇关于使用std :: bind与重载函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!