Why Can't I get value_type From iterator_traits?

  • A+

So I'm doing this:

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; 

I would have expected bar to have the type int. But instead I'm getting an error:

error C2039: value_type: is not a member of std::iterator_traits<_Ty *const >

Is this a problem with the const do I need to strip that or something?


The issue here is with the line

const auto foo = cbegin(arr); 

cbegin(arr) is going to return a int const * (pointer to const int) so applying const to that with const auto foo means foo is a int const * const (const pointer to const int)

std::iterator_traits is only specialized for a T* or T const* so giving it a T* const fails since there is no valid specialization.

You can fix this by removing the constness in the declaration of bar with

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

or you can change foo to

auto foo = std::cbegin(arr); 

if you are okay with it not being const.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: