[英]C++ lambda - capture static member variable
我在靜態類方法中有一個 lambda 函數,如下所示:
void
MyClass::foo() {
auto my_lambda = [](int arg) {
// do stuff
}
}
其中foo
是MyClass
的靜態方法。 現在,在my_lambda
我想引用MyClass
另一個靜態方法bar
。 我怎樣才能做到這一點? 我見過這個問題,但似乎這只適用於非靜態方法,因為靜態方法不能引用this
?
這是我對它的天真看法 - 但我可能誤解了這個問題。
#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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.