C++ variant get() Function



The std::get() function is used to access the value stored in a std::variant object. The std::get() function can be used with an index or a type to retrieve the currently stored value from a std::variant. If an invalid index or type is accessed, it throws std::bad_variant_access.

This function is useful when working with variants, ensuring type safety and flexibility in handling multiple types within a single variable.

Syntax

Following is the syntax for variant std::get() function.

// Get value by index
std::get<N>(std::variant<Types...> &var);
std::get<N>(const std::variant<Types...> &var);
std::get<N>(std::variant<Types...> &&var);
std::get<N>(const std::variant<Types...> &&var);

// Get value by type
std::get<Type>(std::variant<Types...> &var);
std::get<Type>(const std::variant<Types...> &var);
std::get<Type>(std::variant<Types...> &&var);
std::get<Type>(const std::variant<Types...> &&var);

Parameters

  • N : The index of the type stored in the std::variant
  • Type : The exact type stored in the std::variant.
  • var : The std::variant object from which the value is retrieved.

Return Value

The function returns the value stored in the std::variant. If an incorrect index or type is accessed, it throws a std::bad_variant_access exception.

Time Complexity

The time complexity of this function is constant, i.e., O(1).

Example 1

The following example demonstrate, accessing the value by its index using the std::get() which retrieves and prints the value using the index.

#include <iostream>
#include <variant>
int main() {
   std::variant<int, double, std::string> var = 42;
   std::cout << "Value at index 0: " << std::get<0>(var) << std::endl;
   return 0;
}

Output

Output of the above code is as follows

Value at index 0: 42

Example 2

In the following example, we are going to access the value by its type using get() function, which retrieves the stored value using the type.

#include <iostream>
#include <variant>
int main() {
   std::variant<int, double, std::string> var = 3.14;
   std::cout << "Value stored: " << std::get<double>(var) << std::endl;
   return 0;
}

Output

If we run the above code it will generate the following output

Value stored: 3.14

Example 3

Here, we are trying to access an integer using std::get<int>(var) results in an exception, which is caught and displayed.

#include <iostream>
#include <variant>
#include <stdexcept>

int main() {
   std::variant<int, double, std::string> var = "Hello";
   try {
      std::cout << std::get<int>(var) << std::endl; // Incorrect type access
   } catch (const std::bad_variant_access &e) {
      std::cerr << "Exception caught: " << e.what() << std::endl;
   }
   return 0;
}

Output

Following is the output of the above code

Exception caught: bad_variant_access
cpp_variant.htm
Advertisements