How to select iterator type using auto variable?

2019-01-24 06:27发布

问题:

I have a std::unordered_map

std::unordered_map<std::string, std::string> myMap;

I want to get a const iterator using find. In c++03 I would do

std::unordered_map<std::string, std::string>::const_iterator = myMap.find("SomeValue");

In c++11 I would want to use auto instead to cut down on the templates

auto = myMap.find("SomeValue");

Will this be a const_iterator or iterator? How does the compiler decide which to use? Is there a way I can force it to choose const?

回答1:

It will use non-const iterators if myMap is a non-const expression. You could therefore say

#include <type_traits>
#include <utility>

template<typename T, typename Vc> struct apply_vc;
template<typename T, typename U> struct apply_vc<T, U&> {
  typedef T &type;
};
template<typename T, typename U> struct apply_vc<T, U&&> {
  typedef T &&type;
};

template<typename T> 
typename apply_vc<typename std::remove_reference<T>::type const, T&&>::type
const_(T &&t) {
  return std::forward<T>(t);
}

And then

auto it = const_(myMap).find("SomeValue");