Domanda

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.

È stato utile?

Soluzione

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; 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top