简体   繁体   English

map::const_iterator 映射类型不是 const

[英]map::const_iterator mapped type is not const

I'm trying to write an iterator adaptor for a class built on top of a map. I'm having issue when trying to get the mapped type from the iterator type.我正在尝试为构建在 map 之上的 class 编写迭代器适配器。尝试从迭代器类型获取映射类型时遇到问题。 Basically I'd like to get:基本上我想得到:

  • map<Key,Val>::iterator --> Val map<Key,Val>::iterator --> Val
  • map<Key,Val>::const_iterator --> Val const map<Key,Val>::const_iterator --> Val const

Here is a minimal repro.这是一个最小的复制品。

#include <map>
#include <type_traits>
    
template <typename BaseIteratorT>
using ValueType = typename BaseIteratorT::value_type::second_type;
    
// Passes
static_assert(
    std::is_same<ValueType<std::map<double, int>::iterator>, int>::value,
    "bad type for mutable iterator");

// Fails
static_assert(
    std::is_same<ValueType<std::map<double, int>::const_iterator>, const int>::value,
    "bad type for const iterator");

How can I achieve that (C++14)?我怎样才能做到这一点(C++14)?

The value_type of a std::map is std::pair<const Key, T> . std::mapvalue_typestd::pair<const Key, T> The second_type of that pair is just T , not const T , not const T& , just T .该对的second_type只是T ,不是const T ,不是const T& ,只是T Dereferencing a map::const_iterator will return a const pair& reference, but that will not change that pair's second_type to const .取消引用map::const_iterator将返回一个const pair&引用,但这不会将该对的second_type更改为const If you want that, detect whether the iterator's value_type is const or not, such as with std::is_const , and if so then apply const to its second_type , such as with std::add_const .如果需要,请检测迭代器的value_type是否为const ,例如std::is_const ,如果是,则将const应用于其second_type ,例如std::add_const

For almost all practical purposes, types you might want to deduce is tied to some expression, in which case decltype is always the answer对于几乎所有实际目的,您可能想要推断的类型都与某些表达式相关联,在这种情况下, decltype始终是答案

template<typename T>
using mapped_type = std::remove_reference_t<decltype((std::declval<T>()->second))>;

using m = std::map<char, int>;
using i = mapped_type<m::iterator>  // int
using ci = mapped_type<m::const_iterator>  // const int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM