2

I have the following code. I'm trying to eliminate the need for explicitly passing the localization_data_t::language_t type into the lambda argument.

auto language_itr = std::find_if(languages.begin(), languages.end(), [&](const localization_data_t::language_t& language)
{
    return language.code == language_code;
});

I assume there is a way to do this since the type of the objects to be iterated over can be derived by the compiler via the iterator's underlying type. However, I have found no such example in my travels.

Any help would be appreciated.

1
  • 2
    There's always decltype.
    – chris
    Feb 27, 2014 at 23:23

1 Answer 1

8

You can use decltype in C++11:

auto result = std::find_if(v.begin(), v.end(), [](const decltype(*v.begin())& t) { /*   */ });

in C++1y you can just use auto.

auto result = std::find_if(v.begin(), v.end(), [](const auto& t) { /*   */ });

There's also std::iterator_traits but it's more verbose.

3
  • Ah, there's my problem, I'm not using C++14, my compiler is only C++11. :( Glad to know that it's being supported somewhere though. :) Feb 27, 2014 at 23:30
  • @cmbasnett gcc 4.9 will support them and clang 3.4 already does.
    – Rapptz
    Feb 27, 2014 at 23:32
  • I'm on the Apple LLVM 5.0 compiler. auto is not supported for function arguments apparently. :/ Feb 27, 2014 at 23:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.