Modern C++ and Interview Prep · Lesson 32 of 33
Modern C++: optional, variant and std::format
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::optionalstd::variantandstd::visitstd::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;
}
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;
}
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;
}
Asha scored 91 marks (87.5%) [ right] [left ] [ mid ] 00042 | ff | 0b101 | ,,,,,,3.14 Notebook 60.00 Laptop Stand 1499.50
| Spec | Meaning |
|---|---|
{} | 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
| Feature | Standard | Use for |
|---|---|---|
std::string_view | C++17 | read-only string parameters without copies |
| structured bindings | C++17 | auto [k, v] = pair; |
std::span | C++20 | a view of any contiguous array (vector, array, C array) |
<=>, concepts, ranges | C++20 | comparisons, constrained templates, pipelines |
std::expected | C++23 | a value or an error, without exceptions |
std::print | C++23 | formatted printing |
Practice
Try it yourself
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; }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.