Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::iterator not contain std::prev() as a member function?

it++;                       // OK    : Widely used expression for moving iterator.

it_prev = it-1;             // ERROR : What I expected; + - operators never existed
it_prev = std::prev(it)     // OK

it_next3 = it+3;            // ERROR : also, nothing like this exists
it_next3 = std::next(it,3)  // OK

Why does the Iterator class not have + - operators as member functions?

Or std::prev() as a member function to do this?

it_prev = it.prev()         // nothing like this

Is there a special reason for defining the prev function external to the iterator?

like image 969
siamenock Avatar asked Mar 04 '23 02:03

siamenock


1 Answers

If prev() were a member function instead of a free function, it would be less generic since it won't be possible to work with built-in types (e.g., pointers) as iterators:

int *ptr = ...
// ...
ptr.prev() // <-- Pointers don't have member functions!!

whereas with a non-member function template, such as std::prev(), all is needed for it to work with pointers is a specialization that deals with pointers:

int *ptr = ...
// ...
std::prev(ptr); // <-- OK

Pointers also support the increment and decrement operators (i.e., ++ and --), so defining them in iterator classes doesn't hinder generic programming. The same reasoning applies to the binary operators + and -.

like image 134
ネロク・ゴ Avatar answered Mar 16 '23 12:03

ネロク・ゴ