Is it possible to capture by const reference in a lambda expression?
I want the assignment marked below to fail, for example:
#include
I think the capture part should not specify const
, as the capture means, it only need a way to access the outer scope variable.
The specifier is better specified in the outer scope.
const string better_string = "XXX";
[&better_string](string s) {
better_string = s; // error: read-only area.
}
lambda function is const(can't change value in its scope), so when you capture variable by value, the variable can not be changed, but the reference is not in the lambda scope.
There is a shorter way.
Note that there is no ampersand before "best_string".
It will be of a "const std::reference_wrapper<< T >>" type.
[best_string = cref(best_string)](const string& s)
{
best_string = s; // fails
};
http://coliru.stacked-crooked.com/a/0e54d6f9441e6867