c++typesiteratortypenameiterator-traits

Why can't I get value_type from iterator_traits?


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?


Solution

  • Indeed the const is problematic, you do basically:

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

    You might fix it by changing it to

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

    You might use std::decay or std::remove_cv for that:

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

    (or drop const from foo if relevant).