LearnFrenzy
Sign in Take a free test

Modern C++ and Interview Prep · Lesson 32 of 33

Modern C++: optional, variant and std::format

5 min read Updated Nov 7, 2026 Saurabh Samir

C++17 and C++20 added small "vocabulary types" that make everyday code clearer and safer. std::optional says "there may be no value" instead of using −1 or nullptr; std::variant holds one of several types safely; std::format brings Python-style formatting with full type checking. You'll see all three in modern codebases.

In this lesson

  • std::optional
  • std::variant and std::visit
  • std::format
  • A quick tour of other modern features

std::optional

#include <iostream>
#include <map>
#include <optional>
#include <string>

std::optional<int> find_marks(const std::map<std::string, int>& db, const std::string& name) {
    if (auto it = db.find(name); it != db.end()) return it->second;
    return std::nullopt;                                     // "no value"
}

int main() {
    std::map<std::string, int> db{{"Asha", 91}, {"Ravi", 74}};

    if (auto m = find_marks(db, "Asha")) std::cout << "Asha: " << *m << '\n';
    auto meera = find_marks(db, "Meera");
    std::cout << "Meera found? " << std::boolalpha << meera.has_value() << '\n';
    std::cout << "Meera (default 0): " << meera.value_or(0) << '\n';
    return 0;
}

Output

Asha: 91
Meera found? false
Meera (default 0): 0

An optional either holds a value or is empty, and the type itself tells callers to check. Use *opt or opt-> after checking, value_or(default) for a fallback, or value(), which throws std::bad_optional_access if empty.

std::variant and std::visit

#include <iostream>
#include <string>
#include <type_traits>
#include <variant>
#include <vector>

using Cell = std::variant<int, double, std::string>;        // exactly one of these

int main() {
    std::vector<Cell> row{42, 3.14, std::string{"LearnFrenzy"}, 7};

    for (const Cell& c : row) {
        std::visit([](const auto& v) {                      // called with the active type
            using T = std::decay_t<decltype(v)>;
            if constexpr (std::is_same_v<T, int>) std::cout << "int " << v << '\n';
            else if constexpr (std::is_same_v<T, double>) std::cout << "double " << v << '\n';
            else std::cout << "text \"" << v << "\"\n";
        }, c);
    }

    Cell c = 10;
    std::cout << "holds int? " << std::boolalpha << std::holds_alternative<int>(c) << '\n';
    c = std::string{"changed"};
    std::cout << std::get<std::string>(c) << " (index " << c.index() << ")\n";
    return 0;
}

Output

int 42
double 3.14
text "LearnFrenzy"
int 7
holds int? true
changed (index 2)

A variant is a type-safe union: it always knows which type it holds, and std::visit forces you to handle every case. It's a lightweight alternative to inheritance when the set of types is fixed – parsers, JSON values, state machines.

std::format

#include <format>
#include <iostream>
#include <string>
#include <vector>

int main() {
    std::string name = "Asha";
    int marks = 91;
    double pct = 87.456;
    std::cout << std::format("{} scored {} marks ({:.1f}%)\n", name, marks, pct);
    std::cout << std::format("[{:>8}] [{:<8}] [{:^8}]\n", "right", "left", "mid");
    std::cout << std::format("{:05d} | {:x} | {:#b} | {:,>10.2f}\n", 42, 255, 5, 3.14159);

    std::vector<std::pair<std::string, double>> items{{"Notebook", 60}, {"Laptop Stand", 1499.5}};
    for (const auto& [item, price] : items)
        std::cout << std::format("{:<14}{:>10.2f}\n", item, price);
    return 0;
}

Output

Asha scored 91 marks (87.5%)
[   right] [left    ] [  mid   ]
00042 | ff | 0b101 | ,,,,,,3.14
Notebook           60.00
Laptop Stand     1499.50
SpecMeaning
{}default formatting for the type
{:.2f}2 decimal places
{:>8} {:<8} {:^8}right / left / centre in width 8
{:05d}pad with zeros to width 5
{:x} {:b} {:#b}hex / binary / binary with 0b prefix
{:,>10}fill with "," instead of spaces

Unlike printf, mistakes are caught at compile time; unlike iostream manipulators, settings don't "stick". C++23 adds std::print and std::println, which format and print in one call.

Other modern features at a glance

FeatureStandardUse for
std::string_viewC++17read-only string parameters without copies
structured bindingsC++17auto [k, v] = pair;
std::spanC++20a view of any contiguous array (vector, array, C array)
<=>, concepts, rangesC++20comparisons, constrained templates, pipelines
std::expectedC++23a value or an error, without exceptions
std::printC++23formatted printing

Practice

Try it yourself

  1. Write std::optional<double> average(const std::vector<int>&) that returns nullopt for an empty vector, and print the results with std::format.

    Show solution
    #include <format>
    #include <iostream>
    #include <numeric>
    #include <optional>
    #include <vector>
    
    std::optional<double> average(const std::vector<int>& v) {
        if (v.empty()) return std::nullopt;
        return std::accumulate(v.begin(), v.end(), 0.0) / v.size();
    }
    
    int main() {
        for (const auto& v : {std::vector<int>{70, 85, 90}, std::vector<int>{}}) {
            if (auto a = average(v)) std::cout << std::format("average {:.2f}\n", *a);
            else std::cout << "no data\n";
        }
        return 0;
    }

    Output

    average 81.67
    no data

Quick check

What does an empty optional hold?

Nothing – it compares false; use value_or for a default.

How do you run code for whichever type a variant holds?

std::visit with a callable that handles every alternative.

Which format spec prints 3.14159 as "3.14"?

{:.2f}.

Summary

  • optional = a value or nothing; variant = one of several types, handled with visit.
  • std::format gives type-safe, Python-style formatting (std::print in C++23).
  • string_view, span, ranges and expected round out the modern toolkit.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links