如何使用自动变量选择迭代器类型? [英] How to select iterator type using auto variable?

查看:191
本文介绍了如何使用自动变量选择迭代器类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个std :: unordered_map

I have a std::unordered_map

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

我想使用find获取一个const迭代器。在c ++ 03我会做

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

在c ++ 11中,我想使用auto代替缩减模板

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

auto = myMap.find("SomeValue");

这将是一个const_iterator还是迭代器?编译器如何决定使用哪个?是否有一种方法可以强制它选择const?

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?

推荐答案

如果 myMap 是一个非常量表达式。因此,您可以说

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

然后

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

这篇关于如何使用自动变量选择迭代器类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆