Site Tools


wiki:hpp-variant

Table of Contents

<variant>

<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.

Example

This example returns a variant result and safely checks which type is held before accessing it.

// 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;
}
wiki/hpp-variant.md · Last modified: by 127.0.0.1