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

标签 c++ functor

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

相关文章:

c++ - 将文件读入结构 (C++)

c++ - 使用结构的全局 vector

java - 帮助理解 Java 中的函数对象或仿函数

c++ - 如何找到 std::string 的两个 vector 之间的共同词

c++ - 尽管需要函数指针,但使用函数对象

C++:传递具有任意数量参数的函数作为参数

haskell - 非逆变/逆变/可整除/可判定的好例子?

c++ - 如何在 C++ 中创建随机字母数字字符串?

c++ - 在 C++03 中将 std::string 转换为 int

c++ - 为什么我的线程不在后台运行?