Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::get_if: non-throwing variant probe

std::get_if returns a pointer to the requested active std::variant alternative or nullptr without throwing.

Version: C++23

Syntax

template<std::size_t I, class... Types>
constexpr std::add_pointer_t<std::variant_alternative_t<I, std::variant<Types...>>>
std::get_if(std::variant<Types...>* v) noexcept;

template<class T, class... Types>
constexpr std::add_pointer_t<T>
std::get_if(std::variant<Types...>* v) noexcept;

// const-pointer overloads return pointers to const.

std::get_if<I>(&v) selects by index, while std::get_if<T>(&v) selects a type that occurs exactly once. If the variant pointer is non-null and v.index() matches the selection, the result points to the stored object; otherwise it is nullptr. The overload taking const std::variant* returns a pointer to const.

In the example the variant stores the integer 42. The first call yields a valid const int*, while probing for std::string yields nullptr, so the program prints 42 1. The pointer supports inspection without a second call to std::get.

The index must be below the alternative count and the selected type must occur exactly once. Violating either condition is a compile-time error, not a null result. The function is noexcept and also accepts a null variant pointer. The returned pointer expires with the variant or an operation that changes its active alternative; it does not own the object.

Examples

#include <iostream>
#include <string>
#include <variant>

int main() {
    std::variant<int, std::string> value = 42;
    if (const int* number = std::get_if<int>(&value)) {
        std::cout << *number;
    }
    std::cout << ' ' << (std::get_if<std::string>(&value) == nullptr) << '\n';
}

Result

42 1

std::get_if → 42 1

Sources