【问题标题】:C++ lambda - capture static member variableC++ lambda - 捕获静态成员变量
【发布时间】:2019-11-22 21:31:50
【问题描述】:

我在 static 类方法中有一个 lambda 函数,如下所示:

void
MyClass::foo() {
  auto my_lambda = [](int arg) {
    // do stuff
  }
}

其中fooMyClass 的静态方法。现在,在my_lambda 内部,我想引用MyClass 的另一个静态方法bar。我怎样才能做到这一点?我见过this question,但似乎这只适用于非静态方法,因为静态方法不能引用this

【问题讨论】:

  • 我该怎么做?就像你在其他任何地方一样。 ClassName::StaticFunctionName(Parameters);
  • 您实际尝试了什么?只需调用 bar 即可按预期工作,因为它是一个静态方法。无需捕捉任何东西。
  • 标题与内容不匹配..静态方法是全局函数,静态变量有点不同,但都可以通过名称获得?
  • 您不需要this 来访问静态方法。所以简单地捕捉正常的方式。

标签: c++ c++11


【解决方案1】:

这是我的幼稚看法 - 但我可能误解了这个问题。

#include <iostream>

class MyClass {
private:
    static int variable;                                // just some common data

public:
    static void another(int dest) {                     // receiver
        std::cout << "I'm alive: " << dest << "\n"; 
    }
    static void foo();
};

int MyClass::variable = 4;                              // 

void MyClass::foo() {
    auto my_lambda = [](int arg) {
        another(arg + variable);                        // reference another static method
    };
    my_lambda(123);
}

int main() {
    MyClass apa;

    apa.foo();
}

I'm alive: 127

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多