Extend C++ lambda expressions with auxiliary variables
Auxiliary variables are useful for giving per instance scoped variables to the lambda and it's also the only way to move data inside the lambda. i.e. something like (notice the semi-colons):
string str = "asdfasdfasdfasdfasdfasdf";
string s2;
[&; auto s = move(str); const size_t n = s.length()*4] {
s2 += s;
s2.resize(n, '!');
}();
cout << str << endl << s2 << endl;
This example gets treated as if you wrote:
struct gensym {
string &s2;
mutable string s;
const size_t n;
bleh(string &s2, const string &str) :
s2(s2), s(move(str)), n(s.length()*4)
{}
void operator() const
{
s2 += s;
s2.resize(n, '!');
}
};
string str = "asdfasdfasdfasdfasdfasdf";
string s2;
gensym(s2, str)();
cout << str << endl << s2 << endl;
2 comments
-
John M. Długosz
commented
Your n should simply be inside the braces, and s can be defined as a parameter rather than a capture.
-
lrdxgm
commented
I vote against this. Nothing stops you from adding these lines before your lambdas, and it just clutters up the code - If you really want this, you might as well create a standard function object with operator().