skip to content
Ivan's wiki
Site Tools
Search
Tools
Show pagesource
Backlinks
Recent Changes
Media Manager
Sitemap
>
Recent Changes
Media Manager
Sitemap
hpp-variant
This page is read only. You can view the source, but not change it.
# <variant> **[<variant>](https://en.cppreference.com/w/cpp/header/variant)** is a type-safe union: it holds a value of one of the possible types (C++17). Use `std::holds_alternative<T>(v)` to check which type is held, and `std::get<T>(v)` to access the value (throws if wrong type). It's more elegant than `std::any` when you know the set of possible types in advance. This example returns a variant result and safely checks which type is held before accessing it. ```cpp // compile: g++ -std=c++17 -o variantexample variantexample.cpp // run: ./variantexample // description: type-safe union with variant #include <variant> #include <iostream> #include <string> std::variant<int, double, std::string> process() { return std::string("hello"); } int main() { auto result = process(); if (std::holds_alternative<std::string>(result)) { std::cout << "got string: " << std::get<std::string>(result) << "\n"; } return 0; } ```
Page Tools
Show pagesource
Backlinks
Back to top