C++ Library - <variant>



The <variant> header in C++, provides a type-safe union called std::variant that allows us to work with multiple data types at a time. This header is part of the general utility library. The std::variant keeps track of the currently held type and ensures safe access. We can easily handle the contained type using std::visit.

Including <variant> Header

Before using any function of the <variant> header, we need to include it by using the following command.

#include <variant>

Functions of <variant> Header

Below is list of all functions from <variant> header.

Accessor Functions

These functions allows us to access and manipulate the values contained inside a std::variant: ( often a function or functor).

S.NO Function & Description
1 visit()

This function calls the provided functor(function object) with the arguments held by one or more variants.

2 holds_alternative()

This function checks if a variant currently holds a given type.

3 get()

This function reads the value of the variant given the index or the type (if the type is unique), throws on error.

4 get_if()

This function obtains a pointer to the value of a pointed-to variant given the index or the type (if unique), returns null on error.

Accessing the value

In the following example, we are going to use the get function to access the value of varient object.

#include <iostream>
#include <variant>

int main() {
   std::variant<int, double> myVariant = 42; 
   int value = std::get<int>(myVariant);  
   std::cout << "The value is: " << value << std::endl;
   return 0;
}

Following is the output of the above program −

The value is: 42
Advertisements