【问题标题】:Converting a lambda function to a functor structure with mixed lambda-introducer and parameter list将 lambda 函数转换为具有混合 lambda-introducer 和参数列表的函子结构
【发布时间】: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 的可变部分等效?

标签: c++ lambda functor


【解决方案1】:

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

因此,不带const 的调用运算符等效于mutable lambda,带const 限定符的调用运算符等效于不带mutable 的lambda。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    相关资源
    最近更新 更多