Modern C++ Features
ExampleC++
#include <iostream>
#include <map>
#include <optional>
#include <string>
#include <tuple>
#include <variant>
using namespace std;
enum class Color { Red, Green, Blue };
optional<int> parse(const string &s) {
try { return stoi(s); } catch (...) { return nullopt; }
}
int main() {
Color c = Color::Green;
cout << (c == Color::Green) << " " << static_cast<int>(c) << endl;
auto r1 = parse("42");
auto r2 = parse("abc");
cout << r1.value_or(-1) << " " << r2.value_or(-1) << endl;
tuple<string, int> person{"Ada", 36};
auto [name, age] = person;
cout << name << " " << age << endl;
variant<int, string> v = "text";
cout << holds_alternative<string>(v) << endl;
map<string, int> m{{"a", 1}, {"b", 2}};
if (auto it = m.find("b"); it != m.end()) cout << it->second << endl;
constexpr int N = 5 * 5;
static_assert(N == 25, "math works");
cout << N << endl;
return 0;
}Output
1 1 42 -1 Ada 36 1 2 25
enum class keeps enum names scoped, optional models "maybe a value", structured bindings unpack tuples, and constexpr computes at compile time.
Quick check
What does std::optional represent?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.