gpt4 book ai didi

c++ - 仿函数:将 std::function 包装在一个类中

转载 作者:搜寻专家 更新时间:2023-10-31 01:44:19 24 4
gpt4 key购买 nike

假设我正在编写一个库,该库应该提供一些默认计算(函数),但允许用户在编译时提供自己的计算(函数)。例如,假设库提供了一个返回参数乘以 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 参数。

让你的默认函数static来避免这种情况。

关于c++ - 仿函数:将 std::function 包装在一个类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23683546/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com