Learn how to use std::optional, std::variant, and std::any in C++17. These features provide ways to handle optional values, multiple types, and any type of value, enhancing type safety and flexibility in your code.
C++, C++17, std::optional, std::variant, std::any, type safety, programming, examples
// Example of std::optional
#include <optional>
#include <iostream>
std::optional getValue(bool returnValue) {
if (returnValue) {
return 42;
} else {
return std::nullopt; // No value
}
}
int main() {
auto value = getValue(true);
if (value) {
std::cout << "Value: " << *value << std::endl;
} else {
std::cout << "No value returned." << std::endl;
}
return 0;
}
// Example of std::variant
#include <variant>
#include <iostream>
std::variant getVariant(bool returnString) {
if (returnString) {
return "Hello, World!";
} else {
return 42;
}
}
int main() {
auto var = getVariant(false);
std::visit([](auto&& arg){ std::cout << arg << std::endl; }, var);
return 0;
}
// Example of std::any
#include <any>
#include <iostream>
std::any getAnyValue() {
return 3.14; // can store different types
}
int main() {
auto value = getAnyValue();
try {
std::cout << std::any_cast(value) << std::endl; // Cast to double
} catch (const std::bad_any_cast& e) {
std::cout << "Bad cast!" << std::endl;
}
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?