捕获const这个

Alo*_*lon 11 c++ lambda c++11

现在我有一个带lambda的对象函数,以便使用我必须使用的成员函数和变量(或者当然捕获所有..):

void MyClass::MyFunc() {

    auto myLambda = [this](){...};
}
Run Code Online (Sandbox Code Playgroud)

有没有办法明确表示捕获const这个?我知道我可以:

void MyClass::MyFunc() {
    MyClass const* const_my_class = this;
    auto myLambda = [const_my_class](){...};
}
Run Code Online (Sandbox Code Playgroud)

谢谢.

mas*_*oud 4

根据标准 (N3485) 中的\xc2\xa75.1.2 , lambda-capture的定义 为:\n

\nlambda-capture:\n capture-default\n capture-list\n capture-default , capture-list\ncapture-default:\n &\n =\ncapture-list:\n capture ... opt\n capture -list , capture ... opt\ncapture:\n 标识符\n 和标识符\n 这个\n

\n\n

因此,捕获列表中只能有=, &, this,标识符,& 标识符。您不能有表达式,例如转换this为 a const。

\n\n

高版本的捕获列表中-std=c++1y可以使用一些简单的表达式( ),例如:

\n\n
auto myLambda = [self = static_cast<MyClass const*>(this)](){\n\n    // Use `self` instead of `this` which is `const`\n\n};\n
Run Code Online (Sandbox Code Playgroud)\n\n

当然,它不像捕获一样this可以像局部变量一样访问成员。

\n