ProblemsSTL MasteryOne iterator, two constnesses
AdvancedSTL Mastery

One iterator, two constnesses

Context

Writing two nearly identical iterator classes is duplication, so containers use one template with a bool parameter — std::deque does the same. The converting constructor is the subtle part: iterator must convert to const_iterator (callers expect it), but if the same constructor also works backwards, anyone holding a const_iterator can write through the container.

Task

The container has one iterator template for both cases: Iter<false> is mutable, Iter<true> is const. The converting constructor currently allows conversion in BOTH directions — const_iterator silently becomes iterator, and const protection is gone. Constrain it: non-const → const converts, the reverse must not compile.

Constraints

  • iteratorconst_iterator conversion works
  • const_iteratoriterator must NOT compile
  • Reading works through both; writing only through iterator
  • Keep one iterator template (do not split it into two classes)

Before you code

  • Why does the unconstrained template constructor accept both directions?
  • Which condition on (IsConst, OtherIsConst) describes exactly the allowed conversions?
  • How does std::enable_if remove a constructor from the candidate set?

Tests

  • #1Mutable iteration writes
  • #2iterator converts to const_iterator
  • #3const_iterator does NOT convert back(expects compile error)
  • #4Writing through const_iterator does not compile(expects compile error)

Hints

Hint 1

Write the truth table: false->true allowed, false->false allowed, true->true allowed, true->false forbidden. One boolean expression covers it.

Hint 2

Attach the condition as a default template argument: template <bool OtherIsConst, class = std::enable_if_t<...>>.

Editoriterator-const-conversion.cpp
Results

Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.