pair, tuple, optional, variant & any
std::pair<A, B> (<utility>)
Two values: .first, .second. Used by map elements. std::make_pair or {a, b} to create.
std::tuple<Ts...> (<tuple>)
Any number of values: std::get<0>(t) or std::get<std::string>(t) (if the type is unique). Unpack with structured bindings. std::tie(a, b) = ... assigns into existing variables. Tuples compare lexicographically — handy for multi-key sorting:
return std::tie(a.date, a.amount) < std::tie(b.date, b.amount);
std::optional<T> (<optional>) — maybe a value
has_value(), *opt, opt.value() (throws bad_optional_access), value_or(x), reset(). C++23 adds monadic helpers: and_then, transform, or_else.
std::variant<Ts...> (<variant>) — exactly one of several types
A type-safe union:
std::variant<int, double, std::string> v = 42;
v = "hello"; // now holds a string
std::holds_alternative<std::string>(v); // true
std::get<std::string>(v); // throws bad_variant_access if wrong type
std::get_if<int>(&v); // pointer or nullptr
v.index(); // which alternative (0, 1, 2)
std::visit ✅
Run code for whichever type is active:
std::visit([](const auto& x) { std::cout << x; }, v);
The overloaded lambdas trick gives one handler per type. Variants are a great alternative to inheritance for a closed set of types (payment methods, JSON values, shapes).
std::any (<any>) — any single value
std::any a = 5; a = std::string("x"); · std::any_cast<std::string>(a) (throws bad_any_cast). Loses static type safety; use rarely (plugin data, generic property bags).
Choosing
| Need | Use |
|---|---|
| 2 related values | pair (or a small struct with good names ✅) |
| several values temporarily | tuple |
| value or nothing | optional |
| one of a known set of types | variant |
| truly anything | any |
Example
#include <any>
#include <iostream>
#include <optional>
#include <string>
#include <tuple>
#include <variant>
#include <vector>
template <class... Fs> struct overloaded : Fs... { using Fs::operator()...; };
struct Cash { double amount; };
struct Card { double amount; std::string last4; };
struct Wallet { double amount; std::string provider; };
using Payment = std::variant<Cash, Card, Wallet>;
double fee(const Payment& p) {
return std::visit(overloaded{
[](const Cash&) { return 0.0; },
[](const Card& c) { return c.amount * 0.02; },
[](const Wallet& w) { return w.amount > 1000 ? 10.0 : 0.0; },
}, p);
}
std::optional<double> parse_amount(const std::string& s) {
try { return std::stod(s); } catch (...) { return std::nullopt; }
}
int main() {
std::pair<std::string, int> best{ "Asha", 92 };
std::cout << best.first << " scored " << best.second << '\n';
std::tuple<std::string, int, double> record{ "Ravi", 24, 1250.5 };
auto [name, age, balance] = record;
std::cout << name << ' ' << age << ' ' << balance << ", get<2> = " << std::get<2>(record) << '\n';
std::string n2; int a2;
std::tie(n2, a2, std::ignore) = record; // assign into existing variables
std::cout << "tie: " << n2 << ' ' << a2 << '\n';
for (const char* s : { "450.5", "abc" }) {
auto amount = parse_amount(s);
std::cout << '"' << s << "\" -> " << (amount ? std::to_string(*amount) : "invalid")
<< ", value_or(0) = " << amount.value_or(0) << '\n';
}
std::vector<Payment> payments = { Cash{ 500 }, Card{ 2500, "4821" }, Wallet{ 1500, "Khalti" } };
for (const auto& p : payments) {
std::visit([](const auto& x) { std::cout << "amount " << x.amount; }, p);
std::cout << ", index " << p.index() << ", fee " << fee(p);
if (const Card* c = std::get_if<Card>(&p)) std::cout << " (card ending " << c->last4 << ")";
std::cout << '\n';
}
std::variant<int, std::string> v = 42;
v = std::string("now a string");
std::cout << std::boolalpha << "holds string? " << std::holds_alternative<std::string>(v) << '\n';
try {
std::cout << std::get<int>(v);
} catch (const std::bad_variant_access&) {
std::cout << "get<int> threw bad_variant_access\n";
}
std::any setting = 5;
setting = std::string("dark mode");
std::cout << "any holds: " << std::any_cast<std::string>(setting) << '\n';
return 0;
}
/* Output:
Asha scored 92
Ravi 24 1250.5, get<2> = 1250.5
tie: Ravi 24
"450.5" -> 450.500000, value_or(0) = 450.5
"abc" -> invalid, value_or(0) = 0
amount 500, index 0, fee 0
amount 2500, index 1, fee 50 (card ending 4821)
amount 1500, index 2, fee 10
holds string? true
get<int> threw bad_variant_access
any holds: dark mode
*/