【发布时间】:2019-12-03 02:40:59
【问题描述】:
我正在尝试用仿函数构造函数替换 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限定符。你这样做的具体原因是什么?您可以将属性应用于 lambda。 -
如何在仿函数中使 lambda 的可变部分等效?