Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

c++ - How to select iterator type using auto variable?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...