C++ - std::function 作为仿函数的参数

标签 c++ c++11 lambda std-function

我编写了一个 Event 类作为回调函数的包装器,实现为 std::function。这是它的样子:

class Event
{
public:
    Event() : default_handler([]() {});
    Event(const std::function<void()> handler) : default_handler(handler);

    void SetHandler(std::function<void()> handler)
    {
        custom_handler = handler;
    }

    void operator()(void)
    {
        default_handler();
        custom_handler();
    }

private:
    const std::function<void()> default_handler;
    std::function<void()> custom_handler;
};

然后,在另一个类中,我有一个事件实例:

class Control
{
public:
    Control();

//Should call constructor Event()
    Event myEvent1;
//Should call constructor Event(std::function<void()>)
    Event myEvent2([]() {/*do stuff... */})
};

然而,这不会在 VC++ 上编译,为两个处理程序生成错误 C3646(未知覆盖说明符)和错误 C4430(缺少类型说明符 - 假定为 int),myEvent2 有更多语法错误。我哪里出错了?

最佳答案

当你写作时

Event myEvent2([]() {/*do stuff... */});

编译器将 myEvent2 视为成员函数,而不是构造函数调用。

关于C++ - std::function 作为仿函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38525393/

相关文章:

c++ - 虚函数和 std::function?

c++ - 为什么单纯的C++矩阵乘法比BLAS慢100倍?

使用模板的 C++ 11 异步编程

c++ - 为什么默认情况下 C++1 1's lambda require "mutable"keyword 用于按值捕获?

c# - 在表达式树中使用属性表达式的值

c++ - 将函数作为参数传递的良好做法 : copy, 引用,const 引用?

c++ - 在包含 Eigen 类型的类上使用 ` Eigen::aligned_allocator` on `std::vector`

c++ - 如何在 main 中调用包含对节点的引用的函数

c++ - 将别名模板转换为别名类型

c++ - 使用 extern 的显式实例化声明