假设我正在编写一个库,该库应该提供一些默认计算(函数),但允许用户在编译时提供自己的计算(函数)。 例如,假设库提供了一个返回其参数乘以 3 的函数,但用户可以提供自己的函数。
考虑以下程序(被视为 MWE):
float myFunction( float v ) // the function the user needs
{
return v*2;
}
int main()
{
FuncWrapper f;
cout << "default: " << f(2) << endl; // should print "6"
f.AssignFunction( myFunction );
cout << "now is: " << f(2) << endl; // should print "4"
}
所以我构建了一个仿函数 FuncWrapper
来包装 std::function
,按照建议also here :
struct FuncWrapper
{
std::function<float(float)> foo; // the function used
float def( float v ) // the default behaviour member function definition
{
return v*3;
}
float operator()( float v ) // call of function
{
return foo(v);
}
void AssignFunction( float (*uf)(float) ) { foo = uf; }
// constructor: initializes to default function
FuncWrapper() : foo(&FuncWrapper::def) {}
};
在我的机器(gcc 4.6.3)上使用-std=c++0x
,我收到非人类可读的错误消息,如 this other answer 中所述。 。为了方便起见,代码是 runnable here 。似乎是 gcc 4.8,并且它不喜欢构造函数(以及其他错误......):
main.cpp: In constructor 'FuncWrapper::FuncWrapper()':
main.cpp:27:64: error: no matching function for call to 'std::function<float(float)>::function(float (FuncWrapper::*)(float))'
为什么这个赋值是非法的?我有searched对于此主题,可能关键字错误,但没有找到任何相关内容。
有什么线索吗?或者一个更简单的解决方案,也许没有 std::function
但有一个函数指针?
最佳答案
在示例代码中,您尝试将成员函数分配给带有签名 float(float)
的 std::function
。这两者不兼容,因为成员函数具有不同的调用约定:它需要一个 this
参数。
将默认函数设为静态
以避免这种情况。
关于c++ - 仿函数:将 std::function 包装在类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23683546/