Jim*_*ies 11 c++ iterator auto c++11
我有一个std :: unordered_map
std::unordered_map<std::string, std::string> myMap;
Run Code Online (Sandbox Code Playgroud)
我想使用find获取一个const迭代器.在c ++ 03中我会这样做
std::unordered_map<std::string, std::string>::const_iterator = myMap.find("SomeValue");
Run Code Online (Sandbox Code Playgroud)
在c ++ 11中,我希望使用auto来减少模板
auto = myMap.find("SomeValue");
Run Code Online (Sandbox Code Playgroud)
这是const_iterator还是迭代器?编译器如何决定使用哪个?有没有办法可以强迫它选择const?
如果myMap
是非const表达式,它将使用非const迭代器.你可以这样说
#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);
}
Run Code Online (Sandbox Code Playgroud)
然后
auto it = const_(myMap).find("SomeValue");
Run Code Online (Sandbox Code Playgroud)