我在玩函数指针与std::function的比较,并遇到了以下问题。
让我们考虑一下折页代码:
#include <cmath>
#include <functional>
// g++ -std=c++17 SF.C -o SF
// clang++ -std=c++17 SF.C -o SF
int main()
{
typedef double (*TpFunctionPointer)(double) ;
TpFunctionPointer pf1 = sin; // o.k.
TpFunctionPointer pf2 = std::sin; // o.k
TpFunctionPointer pf3 = std::riemann_zeta; // o.k
std::function< double(double) > sf1( sin ); // o.k
std::function< double(double) > sf2( std::sin ); // fails
std::function< double(double) > sf3( std::riemann_zeta ); // fails
}用g++ v8.2或clang v7.0编译函数指针pf1、pf2、pf3和sf1都很好。然而,对于sf2和sf3,我会收到相当长的错误消息,例如:
SF.C:17:47: error: no matching function for call to ‘std::function<double(double)>::function(<unresolved overloaded function type>)’
std::function< double(double)> sf2( std::sin ); // fails这是故意的行为吗?
sf2和sf3不应该没事吗?
发布于 2019-01-14 13:39:55
有std::sin (有,但这不是您想要的),编译器不知道您想要哪一个,尽管只有一个可以成功绑定到您的std::function类型!C++在这个意义上不做反向查找,…
…除非是这样的! on a function pointer type是一个例外,这正是您在这里所需要的:
std::function<double(double)> sf2(static_cast<double(*)(double)>(&std::sin));在 cppreference documentation page上有一个这样的例子。
与此通用解决方案相比,一些潜在的改进(感谢Nathan ):
std::function<double(double)> sf2(static_cast<TpFunctionPointer>(&std::sin))或
std::function<double(double)> sf2([](double val){ return std::sin(val); });https://stackoverflow.com/questions/54182549
复制相似问题