c++ - 将 lambda 函数转换为具有混合 lambda-introducer 和参数列表的函子结构
问题描述
我正在尝试用仿函数构造函数替换 lambda 表达式(以便对其应用一些属性)。我遇到了一些麻烦 - 我做错了什么?:
void foo_top(std::unique_ptr<type_b> b)
{
type_a a{};
#if 0 // I want to replace this original lambda:
foo([a, b = std::move(b)](uint8_t c) mutable {
a.foo_on_c(c);
b->foo_on_a(a);
});
#else // Trying to replace with an equivalent functor. My attempt:
struct d_functor {
type_a d_a;
std::unique_ptr<type_b> d_b;
d_functor(type_a a, std::unique_ptr<type_b> b) : d_a(a) {
d_b = std::move(b);
}
void operator()(uint8_t c) mutable { // Getting errors here...
d_a.foo_on_c(c);
d_b->foo_on_a(d_a);
}
};
foo(d_functor{a, b});
#endif
}
得到错误:
error: expected ';' at end of member declaration
void operator()(uint8_t c) mutable {
error: expected unqualified-id before '{' token
void operator()(uint8_t c) mutable {
解决方案
成员函数没有mutable
限定符。只要const
不使用限定符,成员函数就可以修改类的成员。
因此,不带的调用运算符const
等价于mutable
lambda,而带const
限定符的调用运算符等价于不带 的 lambda mutable
。
推荐阅读
- java - 如何在 Rxjava 中链接 Singles
- flask - Flask 分页 - 过滤器 - 搜索选项 - 请需要支持
- javascript - 如何将 AJAX 发布响应加载到本身已加载 AJAX 的 div 中?
- python - 当我重新单击 Python tkinter 应用程序中的执行按钮时如何清除输出
- ruby-on-rails - 如何在嵌套表单中接受数组参数?
- python - Python:循环数据时继续通过“RuntimeError”
- reactjs - 引导表获取数据的速度不够快
- vlang - 我可以在 Mac OS 中安装 vlang 吗?
- arrays - 将 fromiter 与 arcpy 光标一起使用时出现 Numpy 错误
- openlayers - 扩展 OpenLayers 交互时无法在打字稿中声明事件类型