ProblemsModern C++Three types in one array
ExpertModern C++

Three types in one array

Context

Before std::variant existed, heterogeneous slots were built exactly like this: a tag plus storage, with a proxy that assigns, reports the tag and converts back. The exam strips it to three known types — enough to meet every mechanism a real variant needs.

Task

BarFooIntArray<N> stores N slots, each holding a Bar, a Foo or an int. arr[i] = Bar{} assigns; arr[i].IsBar()/IsFoo()/IsInt() report what is inside; Bar b = arr[0] and int x = arr[2] convert back. A miniature variant built by hand.

Constraints

  • Assignment of Bar{}, Foo{} or an int into arr[i] works
  • Exactly one of IsBar/IsFoo/IsInt is true per slot, matching the last assignment
  • Conversions back (Bar b = arr[i]; int x = arr[j];) return the stored value for int
  • No std::variant / std::any under the hood

Before you code

  • Why is a plain enum tag enough storage discrimination here?
  • What does the proxy return so both assignment and IsBar() work on arr[i]?
  • What does std::variant add that this hand-rolled version lacks?

Tests

  • #1Tags follow assignments
  • #2Conversions back, int keeps its value
  • #3Reassignment switches the tag

Hints

Hint 1

A slot is a tag enum plus an int payload (Bar and Foo carry no data). The proxy points at the slot.

Hint 2

Three operator= overloads set the tag; three conversion operators go back. Only int needs real storage.

Editorbarfoo-array.cpp
Results

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