This question is related to this previous one , where it was noted that init-capture mutablelambdas are incompatible with the Boost and iterator ranges transformfor some rather hidden and deeply nested errors typedefthat may or may not be easily resolved by hacking Boost.Range sources.
The accepted answer suggests storing the lambda in the object std::function. To avoid a potential lack of functions virtual, I wrote two functional objects that could serve as potential jobs. They are MutableLambda1also called MutableLambda2in the code below.
#include <iostream>
#include <iterator>
#include <vector>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
struct MutableLambda1
{
int delta;
template<class T> auto operator()(T elem) { return elem * delta++; }
};
struct MutableLambda2
{
mutable int delta;
template<class T> auto operator()(T elem) const { return elem * delta++; }
};
template<class R, class F>
auto scale(R r, F f)
{
return r | boost::adaptors::transformed(f);
}
int main()
{
auto lam = [delta = 1](auto elem) mutable { return elem * delta++; };
auto rng = std::vector<int>{ 1, 2, 3, 4 };
boost::copy(scale(rng, MutableLambda2{1}), std::ostream_iterator<int>(std::cout, ","));
}
Live Example, lam MutableLambda1, 1, 4, 9, 16 MutableLambda2.
5.1.2 - [expr.prim.lambda]
5 [...] const (9.3.1) , - -- mutable. [...]
11 init-capture , init-capture . -, mutable. [...]
, MutableLambda2 , lambda mutable init-capture.
- init-capture
mutable lambdas , (.. )? mutable const ?- (bonus), Boost
transform , operator() const?