CodeTheRobot

C++ Intermediate · Lesson 12 of 27

std::optional and std::variant

Values that may be missing, and values that are one of several types.

Estimated time · 45–75 min

Learning goals

What you will understand

  • Explain std::optional and std::variant in your own words
  • Use it in a small robotics example
  • Verify the result instead of assuming it worked

Understand the idea first

The mental model

std::optional<T> holds a T or nothing, replacing magic values such as -1 for 'no reading'. Test it with if (opt) or has_value(), read it with * or value_or(default).

std::variant<A, B, C> holds exactly one of several types at a time, and std::visit calls the right code for the active one. Together they give safe, self-describing types, for example a command that is either a Stop, a MoveTo or a SetSpeed.

Guided lesson

Work through these steps

  1. 1.

    Read the std::optional and std::variant example and identify what each line owns or changes.

  2. 2.

    Create a small source file, compile with -std=c++17 and warnings enabled, and run it.

  3. 3.

    Change one input, predict the result before running, then compare the output.

  4. 4.

    Record one compiler or runtime error and explain the correction in your own words.

Worked example

Read it before you run it

#include <optional>
// Header for std::optional.
#include <variant>
// Header for std::variant and std::visit.
std::optional<double> reading;
// Starts empty: no value yet.
reading = 21.5;
// Now it holds a value.
std::cout << reading.value_or(-1.0) << '\n';
// Prints 21.5; would print -1 if empty.
struct Stop {}; struct MoveTo { double x; }; struct SetSpeed { double v; };
// Three command types.
using Command = std::variant<Stop, MoveTo, SetSpeed>;
// A Command is exactly one of the three.
Command cmd = MoveTo{1.5};
// Store a MoveTo.
std::visit([](const auto& c) {
// Call the lambda with whichever alternative is stored.
  if constexpr (std::is_same_v<std::decay_t<decltype(c)>, MoveTo>) std::cout << "move\n";
// Choose code by the active type at compile time (C++17 if constexpr).
}, cmd);
// Pass the variant to visit.

What the example is doing

  1. 1.Read declarations from right to left: identify each value's type, name, and initial value.
  2. 2.Follow the data through each expression before considering syntax shortcuts.
  3. 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.

Watch it run · Values in memory

See what this code does

The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.

motor speed030x1070x1410x1890x1c40x2060x2420x2880x2c*p += 10VALUES IN MEMORY

Demo for std::optional and std::variant. Expected result: move 1.5 -1

Practice code

Now type it yourself

Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice

#include <iostream>
#include <optional>
#include <variant>

struct Stop {};
struct MoveTo {
  double x;
};

int main() {
  std::variant<Stop, MoveTo> cmd = MoveTo{1.5};
  // TODO: use std::get_if<MoveTo>(&cmd): print "move x" when it holds a MoveTo, otherwise "stop"
  std::optional<double> reading;
  std::cout << reading.value_or(-1.0) << '\n';
  return 0;
}

Expected output

move 1.5
-1
Stuck? Show the full solution (try it yourself first)
#include <iostream>
#include <optional>
#include <variant>

struct Stop {};
struct MoveTo {
  double x;
};

int main() {
  std::variant<Stop, MoveTo> cmd = MoveTo{1.5};
  if (auto* m = std::get_if<MoveTo>(&cmd)) std::cout << "move " << m->x << '\n';
  else std::cout << "stop\n";
  std::optional<double> reading;
  std::cout << reading.value_or(-1.0) << '\n';
  return 0;
}

Expected result

How you know it worked

  • After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
  • Changing the stated input produces the result you predicted.

Practical exercise

Apply the lesson

Model robot commands as std::variant<Stop, MoveTo, SetSpeed> and write a handler with std::visit that prints a description for each. Add a function returning std::optional<Command> that parses a string, and test a bad string.

Before you continue

  • The program builds with -std=c++17 and no warnings
  • You can explain the key rule without reading the example
  • The normal and edge cases both have recorded results

If something goes wrong

The compiler reports that a name or type is unknown.

Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.

The program runs but the value is wrong.

Print the inputs and intermediate values, then check conversions, units, and collection order.