CKTIS / C++
std::iterator_traits — iterator-associated types
std::iterator_traits<I>, declared in <iterator>, exposes types describing an iterator, including a raw pointer. It supports container-independent algorithms and distinguishes the value type from the type produced by dereferencing.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <iterator>
std::iterator_traits<I>
typename std::iterator_traits<I>::value_typestd::iterator_traits<I> is a class template from <iterator> for obtaining iterator type information at compile time. Typical members are value_type (value type), difference_type (difference type), reference (dereference result type), pointer (pointer type), and iterator_category (category for classic algorithms).
For const int*, value_type is int, while reference is const int& and pointer is const int*. The specialization for pointers to objects also exposes iterator_concept: it is std::contiguous_iterator_tag, although iterator_category remains std::random_access_iterator_tag. These tags are not interchangeable.
The primary template uses an iterator's nested types or, when specific requirements are met, deduces missing information. Not every type receives all members; some output iterator types can have members equal to void. Also, do not assume that reference always denotes an ordinary reference—it can be a proxy type.
In templates, typename std::iterator_traits<I>::value_type identifies a dependent name as a type. In concept- and ranges-based code, also consider std::iter_value_t<I>, std::iter_difference_t<I>, and std::iter_reference_t<I>; the last alias comes directly from the dereference expression rather than the reference member.
Examples
#include <iostream>
#include <iterator>
#include <type_traits>
int main() {
const int values[] = {2, 4, 6};
using Traits = std::iterator_traits<const int*>;
static_assert(std::is_same_v<Traits::value_type, int>);
static_assert(std::is_same_v<Traits::reference, const int&>);
static_assert(std::is_same_v<Traits::pointer, const int*>);
static_assert(std::is_same_v<Traits::iterator_category,
std::random_access_iterator_tag>);
static_assert(std::is_same_v<Traits::iterator_concept,
std::contiguous_iterator_tag>);
Traits::value_type sum = 0;
Traits::difference_type count = (values + 3) - values;
for (const int* it = values; it != values + 3; ++it) {
sum += *it;
}
std::cout << sum << ' ' << count << '\n';
}
Result
12 3
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.