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

Jon*_*Mee 13 c++ types iterator typename iterator-traits

我这样做:

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;
Run Code Online (Sandbox Code Playgroud)

我本来期望bar有这种类型int.但相反,我得到一个错误:

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

这是const我需要剥离那个什么的问题吗?

Nat*_*ica 19

这里的问题是与线

const auto foo = cbegin(arr);
Run Code Online (Sandbox Code Playgroud)

cbegin(arr)将返回一个int const *(指向const int的指针)所以应用于const带有const auto foo均值的指针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
Run Code Online (Sandbox Code Playgroud)

或者你可以foo改为

auto foo = std::cbegin(arr);
Run Code Online (Sandbox Code Playgroud)

如果你对它没有好的话const.


Jar*_*d42 8

确实const有问题,你基本上做了:

std::iterator_traits<const int* const>::value_type // incorrect due to the last const
Run Code Online (Sandbox Code Playgroud)

您可以通过将其更改为修复它

std::iterator_traits<const int*>::value_type // Correct
Run Code Online (Sandbox Code Playgroud)

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

const typename std::iterator_traits<std::remove_cv_t<decltype(foo)>>::value_type
Run Code Online (Sandbox Code Playgroud)

(如果相关const,foo则删除).