gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:30:32 24 4
gpt4 key购买 nike

我编写了一个 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/

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