4

I'm trying to write a single iterator class that can cover both const_iterator and iterator classes to avoid code duplication.

While reading some other questions, I came across this post that asks the exact question I want. The best response was this article that does a decent job explaining what I need to do in a paragraph, but refers to examples in books that I don't have. My attempt to implement what is described is as follows:

      template<bool c=0> //determines if it is a const_iterator or not
      class iterator{
         typedef std::random_access_iterator_tag iterator_category;
         typedef T value_type;
         typedef T value_type;
         typedef std::ptrdiff_t difference_type;
         typedef (c ? (const T*) : (T*)) pointer; //problem line
         typedef (c ? (const T&) : (T&)) reference; //problem line
      public:
         operator iterator<1>(){ return iterator<1>(*this) }
         ...
      }

I can't figure out how to use the ternary operator to determine the typedef. The specified lines get the compiler error "expected ‘)’ before ‘?’ token". Am I interpreting the article wrong?

Also, it says to write a converting constructor so that all my const functions can have non-const parameters converted. Doesn't that mean that the program has to tediously construct new iterators for every parameter when using const_iterators? It doesn't seem like a very optimal solution.

Community
  • 1
  • 1
Suedocode
  • 2,504
  • 3
  • 23
  • 41
  • 1
    Possible duplicate of [How to avoid code duplication implementing const and non-const iterators?](http://stackoverflow.com/questions/2150192/how-to-avoid-code-duplication-implementing-const-and-non-const-iterators) or minimize the question to the `?` problem ;-) – Ciro Santilli OurBigBook.com Dec 23 '16 at 07:36

1 Answers1

4

The ternary operator doesn't work like that on types. You can use std::conditional instead:

typedef typename std::conditional<c ,const T*, T*>::type pointer; 
Pubby
  • 51,882
  • 13
  • 139
  • 180
  • 1
    Argh!! When he says "compile-time ?: operator" it's so misleading! I feel stupid now. Thank you very much! – Suedocode Mar 03 '13 at 06:48
  • 1
    Although this works, I am always fascinated by the amount of extra code written to avoid some code duplication. :-) When you end up having more code you haven't reduced the complexity - which was the original goal. See [this "solution"](http://stackoverflow.com/a/15132173/597607) for an example on how to use two complex casts to save one `return n;`. – Bo Persson Mar 03 '13 at 09:22