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

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?

asked Feb 1 by anonymous

1 Answer

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.

answered Feb 1 by Eric Z Ma (44,280 points)

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...