+ 2
Iterators in C++
How does std::begin() and std::end() functions know the data type of the object they encounter? Cause when I dereference them, they seem to work just fine. Also, how are they implemented?
3 ответов
+ 5
Templates allow std::begin() and std::end() (and in the cases of most STL data structures, the iterators too) to work with any data type. The rest of the 'magic' is done by the decltype keyword.
See the declaration of std::begin() in the cppreference link given by Martin Taylor (https://en.cppreference.com/w/cpp/iterator/begin)
template <class C>
auto begin(C& c) -> decltype(c.begin())
The template allows object of any type 'C' to be recieved as a reference (C&). Then using the decltype keyword, you specify the return type to be "the type of the value returned by c.begin()"
The decltype specifier
https://en.cppreference.com/w/cpp/language/decltype
+ 1
Okay thanks, I got it!