AdvancedLesson 18 of 18
Modern C++: optional, variant, string_view and constexpr – C++
Expressive building blocks from C++17/20 for safer and faster code.
std::optional<T> models "maybe a value" – without null pointers or magic values like -1. std::variant is a type-safe union, and std::visit handles each alternative.
#include <iostream>
#include <optional>
#include <string>
#include <variant>
#include <vector>
std::optional<int> finde_index(const std::vector<int>& v, int wert) {
for (std::size_t i = 0; i < v.size(); ++i)
if (v[i] == wert) return static_cast<int>(i);
return std::nullopt;
}
int main() {
std::vector<int> v{4, 8, 15};
if (auto idx = finde_index(v, 8)) std::cout << "found at " << *idx << '\n'; // 1
std::cout << finde_index(v, 99).value_or(-1) << '\n'; // -1
std::variant<int, double, std::string> w = 3.14;
std::visit([](const auto& x) { std::cout << x << '\n'; }, w); // 3.14
w = std::string("hello");
std::visit([](const auto& x) { std::cout << x << '\n'; }, w); // hello
}std::string_view (and std::span) are non-owning views of text or contiguous data, respectively: cheap to pass, no copy. The catch: the original must live longer.
#include <iostream>
#include <span>
#include <string_view>
#include <vector>
std::size_t zaehle_a(std::string_view text) {
std::size_t n = 0;
for (char c : text) if (c == 'a') ++n;
return n;
}
int summe(std::span<const int> daten) {
int s = 0;
for (int x : daten) s += x;
return s;
}
int main() {
std::vector<int> v{1, 2, 3, 4};
std::cout << zaehle_a("banana") << '\n'; // 3 (no std::string needed)
std::cout << summe(v) << '\n'; // 10
int feld[] = {5, 5};
std::cout << summe(feld) << '\n'; // 10
}constexpr moves computations to compile time. This lets you generate tables, constants and checks at no runtime cost; consteval even enforces it.
#include <array>
#include <iostream>
constexpr int fib(int n) { return n < 2 ? n : fib(n - 1) + fib(n - 2); }
static_assert(fib(10) == 55);
constexpr std::array<int, 5> quadrate() {
std::array<int, 5> a{};
for (int i = 0; i < 5; ++i) a[i] = i * i;
return a;
}
int main() {
constexpr auto q = quadrate(); // already computed at compile time
std::cout << q[4] << ' ' << fib(10) << '\n'; // 16 55
}[[nodiscard]],[[maybe_unused]],[[likely]]– attributes for the compiler and readersenum class– type-safe enumerations without implicit conversion toint- Structured bindings:
auto [a, b] = paar; std::format(C++20) andstd::print(C++23) for formatting- Three-way comparison
<=>(C++20) generates all comparison operators at once
TipRule for parameters: only reading text →
std::string_view; only reading data → std::span<const T>; optional result → std::optional<T>; several types → std::variant. First check whether the standard library can already do it.