C++ variant get_if() Function
The std::get_if() function is used to access a value stored in a std::variant. It returns a pointer to the value if the variant currently holds the requested type; otherwise, it returns a nullptr. This function helps avoid exceptions when retrieving values from a variant, making it a safer alternative to std::get().
This function helps in working with variants containing multiple types, allowing for type-safe access without the risk of throwing exceptions.
Syntax
Following is the syntax for variant std::get_if() function.
const T* get_if(std::variant<Types...>* v) noexcept; const T* get_if(const std::variant<Types...>* v) noexcept;
Parameters
- v : Pointer to the std::variant instance.
- T : The type of value to retrieve from the variant.
Return Value
The function returns a pointer to the stored value if T is the currently active type in the variant. Returns nullptr if T does not match the active type.
Time Complexity
The time complexity of this function is constant, i.e., O(1).
Example 1
In the following example, the variant initially holds an int, and std::get_if<int>() successfully retrieves a pointer to the stored value. Since the type matches, it prints the integer value.
#include <iostream>
#include <variant>
int main() {
std::variant<int, double> v = 42; // The variant holds an int
if (int* ptr = std::get_if<int>(&v)) {
std::cout << "Value: " << *ptr << '\n';
} else {
std::cout << "Type mismatch!" << '\n';
}
return 0;
}
Output
Output of the above code is as follows
Value: 42
Example 2
Here, the variant contains a double, but std::get_if<int>() tries to retrieve an int, which results in nullptr. The mismatch is detected, and the appropriate message is displayed.
#include <iostream>
#include <variant>
int main() {
std::variant<int, double> v = 3.14; // The variant holds a double
if (int* ptr = std::get_if<int>(&v)) {
std::cout << "Value: " << *ptr << '\n';
} else {
std::cout << "Type mismatch!" << '\n';
}
return 0;
}
Output
If we run the above code it will generate the following output
Type mismatch!
Example 3
In the following example, variant stores a Data struct, and std::get_if<Data>() successfully retrieves a pointer to the struct. The stored text is then accessed and printed.
#include <iostream>
#include <variant>
#include <string>
struct Data {
std::string text;
};
int main() {
std::variant<int, Data> v = Data{"Hello, Variant!"};
if (Data* ptr = std::get_if<Data>(&v)) {
std::cout << "Stored text: " << ptr->text << '\n';
} else {
std::cout << "Type mismatch!" << '\n';
}
return 0;
}
Output
Following is the output of the above code
Stored text: Hello, Variant!