[英]const_iterator and constness of const_iterator::value_type
[英]map::const_iterator mapped type is not const
我正在尝试为构建在 map 之上的 class 编写迭代器适配器。尝试从迭代器类型获取映射类型时遇到问题。 基本上我想得到:
这是一个最小的复制品。
#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");
我怎样才能做到这一点(C++14)?
std::map
的value_type
是std::pair<const Key, T>
。 该对的second_type
只是T
,不是const T
,不是const T&
,只是T
。 取消引用map::const_iterator
将返回一个const pair&
引用,但这不会将该对的second_type
更改为const
。 如果需要,请检测迭代器的value_type
是否为const
,例如std::is_const
,如果是,则将const
应用于其second_type
,例如std::add_const
。
对于几乎所有实际目的,您可能想要推断的类型都与某些表达式相关联,在这种情况下, 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.