为什么我不能从iterator_traits获得value_type?

Why can't I get value_type from iterator_traits?

本文关键字:获得 value type traits 为什么 不能 iterator      更新时间:2023-10-16

我正在这样做:

const int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };
const auto foo = cbegin(arr);
const typename iterator_traits<decltype(foo)>::value_type bar = 1;

我本来希望bar有类型 int.但相反,我收到一个错误:

错误 C2039: value_type: 不是 std::iterator_traits<_Ty *const > 的成员

这是我需要剥离它或其他东西const的问题吗?

这里的问题是行

const auto foo = cbegin(arr);

cbegin(arr)将返回一个int const *(指向 const int 的指针),因此使用 const auto fooconst应用于该foo意味着是一个int const * const(指向 const int 的 const 指针)

std::iterator_traits只专门用于T*T const*因此给它一个T* const失败,因为没有有效的专业化。

您可以通过删除 bar 声明中的恒定性来解决此问题

const typename std::iterator_traits<std::remove_cv_t<decltype(foo)>>::value_type

或者您可以将foo更改为

auto foo = std::cbegin(arr);

如果你对它不const没意见.

确实const是有问题的,你基本上是这样做的:

std::iterator_traits<const int* const>::value_type // incorrect due to the last const

您可以通过将其更改为

std::iterator_traits<const int*>::value_type // Correct

您可以使用std::decaystd::remove_cv

const typename std::iterator_traits<std::remove_cv_t<decltype(foo)>>::value_type

(如果相关,请从foo中删除const)。

声明

一个常量限定的迭代器const auto foo = cbegin(arr);是值得怀疑的。对于无法应用operator++()的迭代器,您有什么用?此外,迭代器要求类型int const *const可复制的;因此,变量foo不满足迭代器要求。所以严格来说,foo不是迭代器