How to not use concrete types in lambda function parameters in C++11?
Posted on In QAC++11 requires that lambda function parameters be declared with concrete types. This is sometimes annoying. auto
is really nice, especially when the type is complex like std::vector<std::string>::iterator
is quite long to type. I know C++14 allows auto
in lambda functions. But how to not use concrete types in lambda function parameters in C++11?
In C++11, you may let the compiler infer the type for you by using
decltype(...)
and replace the type declaration with decltype()
.
For example
#include <iostream>
#include <string>
#include <algorithm>
int main ()
{
std::vector<std::string> ss = {"hello", "world"};
std::transform(std::begin(ss), std::end(ss), std::begin(ss), [](decltype(*std::begin(ss)) si) {
return si;
});
return 0;
}
decltype(*std::begin(ss))
infers the concrete type automatically for you so that you don’t need to manually write the concrete type delcaration.