bhylu.com

Advertisements

C++ Tuples and Variants

Return related values together and use variant when a result has one of several distinct shapes.

How it works

A tuple groups a fixed set of possibly different types, while a variant holds one active alternative from a listed set. Structured bindings give tuple elements local names. variant carries its active alternative information and visit selects an appropriate callable overload, avoiding an unchecked manual union tag. Prefer a named struct when field meaning is important to a public API; a tuple of several identical ints can become hard to read. Alternative types should represent useful domain distinctions, not merely hide error handling.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror tuples-variants.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · tuples-variants.cpp

#include <iostream>
#include <tuple>
#include <variant>
#include <string>
#include <type_traits>

int main() {
    auto [stops, minutes] = std::tuple{3, 45};
    std::variant<int, std::string> result{std::string{"route unavailable"}};
    std::cout << "Plan: " << stops << " stops, " << minutes << " minutes\n";
    std::visit([](const auto& value) { std::cout << "Result: " << value << '\n'; }, result);
}

Expected result

Plan: 3 stops, 45 minutes
Result: route unavailable

The tuple fixture is unpacked without remembering numeric get positions. The generic visitor works because both alternatives support stream insertion. std::get of the wrong variant alternative throws; get_if can test without throwing. Some operations can leave a variant valueless by exception, so an advanced public type should account for its actual member exception guarantees.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.

Advertisements