You're just completely missing the point. The need for std::function
is very, very obvious.
std::function
does.How on earth could you ever create a vector that varies at run-time a compile-time fact, like the type contained within it? That's just logically impossible- unless you use an abstraction such as std::function
.
Of course, if you only ever want one lambda type within, then you don't need std::function
at all. This is relatively rare though.
int main() {
auto adder = [](int x) {
return [=](int y) {
return x + y;
};
};
// alternatively- you MUST copy the argument as it will cease to exist
// but once it's in the lambda, you can use "mutable" to allow you to
// modify the copy that each lambda has.
/*
auto adder = [](int x) {
return [=](int y) mutable {
return x += y;
};
};
*/
std::vector adders;
adders.emplace_back(adder(0));
adders.emplace_back(adder(1));
std::for_each(adders.begin(), adders.end(), [](decltype(*adders.begin())& ref) {
std::cout << ref(33);
});
std::cin.get();
}
MSVC won't actually compile this little snippet, but I think that's a bug and judging by the reports of your compiler, I expect that it will compile there and indeed work correctly.