How to not use concrete types in lambda function parameters in C++11?

Posted on In QA

C++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.

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *