< cpp‎ | utility‎ | variant
Utilities library
Language support
Type support (basic types, RTTI)
Library feature-test macros (C++20)
Dynamic memory management
Program utilities
Coroutine support (C++20)
Variadic functions
Debugging support
Three-way comparison
General utilities
Date and time
Function objects
Formatting library (C++20)
Relational operators (deprecated in C++20)
Integer comparison functions
Swap and type operations
Common vocabulary types
Elementary string conversions

Defined in header <variant>
template< class T, class... Types >
constexpr bool holds_alternative( const std::variant<Types...>& v ) noexcept;
(since C++17)

Checks if the variant v holds the alternative T. The call is ill-formed if T does not appear exactly once in Types...


[edit] Parameters

v - variant to examine

[edit] Return value

true if the variant currently holds the alternative T, false otherwise.

[edit] Example

#include <variant>
#include <string>
#include <iostream>
int main()
    std::variant<int, std::string> v = "abc";
    std::cout << std::boolalpha
              << "variant holds int? "
              << std::holds_alternative<int>(v) << '\n'
              << "variant holds string? "
              << std::holds_alternative<std::string>(v) << '\n';


variant holds int? false
variant holds string? true

[edit] See also

returns the zero-based index of the alternative held by the variant
(public member function) [edit]
reads the value of the variant given the index or the type (if the type is unique), throws on error
(function template) [edit]