This is part of my weekly C++ posts based on the daily C++ tips I make at my work. I strongly recommend this practice. If you dont have it in your company start it.
List of all weekly posts can be found here.
1. Locking the lambda type
This trick I saw in
C++ Slack (great place, lots of interesting stuff). Its from
Miro Knejp.
As we know the compiler generates different lambda types for different lambdas even if they are exactly the same:
auto lambda1 = []() {};
auto lambda2 = []() {};
std::cout << typeid(decltype(lambda1)).name() << '\n';
std::cout << typeid(decltype(lambda2)).name() << '\n';
This produces different results. Its implementation specific so it varies between compilers. However sometimes we want to put lambdas in a container and do something. We can use std::function and type erase them but it has some overhead (havent researched what exactly but I will, stay tuned).
So the trick here is to use a helper function that returns a lambda:
auto make_f = [](int multiplyer ) {
return [multiplyer](const int& i) {
return i * multiplyer;
};
};
auto Funcs = std::vector<decltype(make_f(0))>();
Funcs.push_back(make_f(1));
Funcs.push_back(make_f(2));