Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/163.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何使用自动变量选择迭代器类型?_C++_Iterator_C++11_Auto - Fatal编程技术网

C++ 如何使用自动变量选择迭代器类型?

C++ 如何使用自动变量选择迭代器类型?,c++,iterator,c++11,auto,C++,Iterator,C++11,Auto,我有一张无序的地图 std::unordered_map<std::string, std::string> myMap; 这是常量迭代器还是迭代器?编译器如何决定使用哪个?有没有办法强制它选择常量?如果myMap是一个非常量表达式,它将使用非常量迭代器。因此,你可以说 #include <type_traits> #include <utility> template<typename T, typename Vc> struct apply

我有一张无序的地图

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

这是常量迭代器还是迭代器?编译器如何决定使用哪个?有没有办法强制它选择常量?

如果
myMap
是一个非常量表达式,它将使用非常量迭代器。因此,你可以说

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

也许编译器正在进行函数范围的类型推断。。。但是为什么迭代器的常量对您很重要呢?除非我对重载的理解是错误的(或者是错误的),
nonstmap.find
总是返回一个
迭代器。返回类型和您对结果所做的操作(例如,将其传递给
常量迭代器
构造函数)不会影响选择哪个重载。也就是说,如果调用
constMap.find
,它只返回一个
const\u迭代器
。为什么不只返回
template const&const\u(T&T){return T;}
?这个迭代器不适用于非右值,并且会将常量值转换为左值。不太好。我没有考虑后者(为什么要做一些已经是
const
const
?),但无论如何,你都可以用重载来解决这个问题。右值的情况是好的,但我仍在努力思考
apply\u vc
。我知道它的作用,但不知道为什么它是必要的。它将右值保留为右值,将左值保留为左值,以便MemberFunction的ref限定符重载仍然有效。c++17已将std::as_const添加到标头中
auto = myMap.find("SomeValue");
#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");