Scroll to navigation

std::variant_size,std::variant_size_v(3) C++ Standard Libary std::variant_size,std::variant_size_v(3)


std::variant_size,std::variant_size_v - std::variant_size,std::variant_size_v


Defined in header <variant>
template <class T> (1) (since C++17)
struct variant_size; /* undefined */
template <class... Types>

struct variant_size<std::variant<Types...>> (2) (since C++17)

: std::integral_constant<std::size_t, sizeof...(Types)> {
template <class T> class variant_size<const T>; (3) (since C++17)
template <class T> class variant_size<volatile T>; (3) (since C++17)
template <class T> class variant_size<const volatile T>; (deprecated in C++20)

Provides access to the number of alternatives in a possibly cv-qualified variant as
a compile-time constant expression.


2) meets the UnaryTypeTrait requirements with a base characteristic of
std::integral_constant<std::size_t, sizeof...(Types)>
3) meets the UnaryTypeTrait requirements with a base characteristic of
std::integral_constant<std::size_t, variant_size<T>>

Helper variable template

template <class T>
inline constexpr std::size_t variant_size_v = (since C++17)

Inherited from std::integral_constant

Member constants

value sizeof...(Types)
[static] (public static member constant)

Member functions

operator std::size_t converts the object to std::size_t, returns value
(public member function)
operator() returns value
(C++14) (public member function)

Member types

Type Definition
value_type std::size_t
type std::integral_constant<std::size_t, value>


All specializations of std::variant_size satisfy UnaryTypeTrait with base
characteristic std::integral_constant<std::size_t, N> for some N.


// Run this code

#include <any>
#include <cstdio>
#include <variant>

static_assert(std::variant_size_v<std::variant<>> == 0);
static_assert(std::variant_size_v<std::variant<int>> == 1);
static_assert(std::variant_size_v<std::variant<int, int>> == 2);
static_assert(std::variant_size_v<std::variant<int, int, int>> == 3);
static_assert(std::variant_size_v<std::variant<int, float, double>> == 3);
static_assert(std::variant_size_v<std::variant<std::monostate, void>> == 2);
static_assert(std::variant_size_v<std::variant<const int, const float>> == 2);
static_assert(std::variant_size_v<std::variant<std::variant<std::any>>> == 1);

int main() { std::puts("All static assertions passed."); }


All static assertions passed.

See also

variant_alternative obtains the type of the alternative specified by its
variant_alternative_t index, at compile time
(C++17) (class template) (alias template)
std::tuple_size<std::tuple> obtains the size of tuple at compile time
(C++11) (class template specialization)