Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::holds_alternative: test a variant active type

std::holds_alternative<T> non-throwingly tests whether std::variant currently stores its unique T alternative.

Version: C++23

Syntax

template<class T, class... Types>
constexpr bool
std::holds_alternative(const std::variant<Types...>& value) noexcept;

std::holds_alternative<T>(v) returns true when v.index() equals the index of type T in the alternative list. It is constexpr and noexcept and neither reads nor copies the stored value. The declaration requires T to occur exactly once in Types....

The example has std::string as the active alternative. Testing int is false and testing std::string is true, so ordinary bool formatting prints 0 1. After a successful test, retrieve the value with std::get<T>, or obtain a pointer directly with std::get_if<T>.

A repeated type, such as in std::variant<int, int>, cannot be tested with holds_alternative<int>: the program is ill-formed; distinguish those alternatives with index(). A variant can be valueless_by_exception(), in which case every type test is false. A separate test followed by mutation needs normal synchronization when the object is shared across threads.

Examples

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

int main() {
    std::variant<int, std::string> state = std::string{"ready"};
    std::cout << std::holds_alternative<int>(state) << ' '
              << std::holds_alternative<std::string>(state) << '\n';
}

Result

0 1

std::holds_alternative → 0 1

Sources