C++ 23 cheatsheet
C++ 23: Language basics
9 common C++ 23 tasks.
Hello world
The smallest C++ program, printing a line with iostream.
#include <iostream>
int main() {
std::cout << "Hello, world!\n";
}
Loop over a container
Use auto and a range-based for loop. const auto& avoids copying each element.
for (const auto& item : items) {
std::cout << item << '\n';
}
Unpack a pair or struct
Name the parts of a pair, tuple or struct in one declaration.
for (const auto& [name, score] : scores) {
std::cout << name << ": " << score << '\n';
}
Format text
Build a string with placeholders using std::format (C++20).
#include <format>
std::string s = std::format("{} scored {:.1f}%", name, percent);
Pass a string without copying
Take a std::string_view parameter to accept strings and literals cheaply.
void log(std::string_view message) {
std::cout << message << '\n';
}
Define a scoped enum
A strongly typed enum whose names don't leak into the surrounding scope.
enum class Color { Red, Green, Blue };
Color c = Color::Green;
Compute at compile time
A constexpr function can be evaluated while compiling, and static_assert checks it.
constexpr int square(int n) { return n * n; }
static_assert(square(4) == 16);
Declare a variable in an if
Limit a variable's scope to the if and else branches.
if (auto it = scores.find("Ada"); it != scores.end()) {
std::cout << it->second << '\n';
}
Warn when a result is ignored
Mark a function whose return value should be used.
[[nodiscard]] bool save(const std::string& path);