+ 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?

11th Jul 2021, 7:09 AM
Rishi
Rishi - avatar
3 odpowiedzi
+ 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
11th Jul 2021, 8:07 AM
XXX
XXX - avatar
+ 1
Okay thanks, I got it!
11th Jul 2021, 10:08 AM
Rishi
Rishi - avatar