Search code examples
c++templatesiteratorc++14const-iterator

How to make a copy constructor for different types within a template class?


I need to make my Iterator< isConst = false> convert to Iterator<isConst = true>. That is, I need a separate method Iterator< true >(const Iterator< false > &).

My Iterator class:

template < typename T >
template < bool isConst >
class ForwardList< T >::Iterator
{
  using value_type = std::conditional_t< isConst, const T, T >;
  using difference_type = ptrdiff_t;
  using pointer = std::conditional_t< isConst, const T *, T * >;
  using reference = std::conditional_t< isConst, const T &, T & >;
  using iterator_category = std::forward_iterator_tag;

  friend class ForwardList< T >;
private:
  explicit Iterator(node_t *nodePtr): nodePtr_(nodePtr) {}
public:
  Iterator() = default;
  Iterator(const Iterator &other) = default;
  ~Iterator() = default;

  reference operator*() const;
  pointer operator->() const;
  Iterator &operator++();
  Iterator operator++(int) &;
  bool operator==(const Iterator &other) const;
  bool operator!=(const Iterator &other) const;

private:
  node_t *nodePtr_;
};

I tried overloading the copy constructor and specializing the template. I understand that if you split the Iterator into two classes, it can be done, but I don't want to duplicate so much code.


Solution

  • Rather than having a constructor that takes an Iterator<false>, you can have a conversion operator that returns an Iterator<true>.

    operator Iterator<true>() const { return Iterator<true>(nodePtr_); }
    

    You will need to friend class Iterator<false>; to access your private constructor.

    See it live