2

I am trying to use the same variable for both iterator and reverse iterator. However, I cannot find the common base class to do so. I want to do something like this:

string a;
....
string::iterator i;
if (....)
    i = a.begin();
else
    i = a.rbegin();  //Error
....

Is there a good way of doing this?

4
  • 4
    Don't do it. They are two different things. Commented Apr 30, 2018 at 10:46
  • 1
    Can you extract the common code into a template? Commented Apr 30, 2018 at 10:47
  • There is no common base class, so no it will not work. Commented Apr 30, 2018 at 10:52
  • There is no requirement that iterator and reverse_iterator be of compatible types. They are not necessarily classes either, so may not have a common base. Try do have characteristics/traits in common though. Commented Apr 30, 2018 at 10:53

1 Answer 1

7

There is no common type for std::string::iterator and std::string::reverse_iterator.

If you want to choose between them, you will need to have a different function for each type. The simplest way to do that is with a template

E.g.

template <typename Iterator>
void do_stuff(Iterator begin, Iterator end)
{
    ...
}

int main()
{
    string a;
    if (...)
        do_stuff(a.begin(), a.end());
    else
        do_stuff(a.rbegin(), a.rend());
    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.