首页 > 解决方案 > 将 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 {

标签: c++lambdafunctor

解决方案


成员函数没有mutable限定符。只要const不使用限定符,成员函数就可以修改类的成员。

因此,不带的调用运算符const等价于mutablelambda,而带const限定符的调用运算符等价于不带 的 lambda mutable


推荐阅读