Modern Vocabulary Types: std::optional, std::variant & std::any
🔴 Advanced
📖 Definition
Introduced in C++17:
std::optional<T>: Represents a value that may or may not exist (eliminating null pointers).std::variant<T1, T2>: Type-safe tagged union.std::any: Type-safe container for single values of any type.
💡 Code Example
#include <iostream>
#include <optional>
std::optional<int> parseVal(bool valid) {
if (valid) return 42;
return std::nullopt;
}
int main() {
auto res = parseVal(true);
if (res.has_value()) {
std::cout << "Parsed Value: " << *res << "\n";
}
return 0;
}