我正在尝试为构建在 map 之上的类编写迭代器适配器。尝试从迭代器类型获取映射类型时遇到问题。基本上我想得到:
这是一个最小的再现。
#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)?
最佳答案
value_type
的 std::map
是 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
.
关于c++ - map::const_iterator 映射类型不是 const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63696489/