According to the C++23 standard, what is the output of this program?
#include <variant>
#include <iostream>
int main() {
std::variant<int, double, char> v;
std::cout << v.index();
}index() returns the index of the type of the contained value.
0
std::variant can hold a value of any one of its alternative types, or no value. To refer to the alternative types, it uses an index i.
§[variant.ctor]¶1 in the standard:
(...) let
ibe in the range[0, sizeof...(Types)), andTi be the ith type inTypes.
In our case, T0 means int, T1 means double, and T2 means char.
Now what happens if you define a variant without initializing it with a certain type? The default constructor will pick the type T0, in our case int, and value-initialize it.
constexpr variant() noexcept(see below);Effects: Constructs a
variantholding a value-initialized value of typeT0.
Finally, we call index() and print the result. index() returns the index of the type of the contained value. The contained value is an int, aka T0, so 0 is returned.
constexpr size_t index() const noexcept;Effects: If [it doesn't contain a value], returns
variant_npos. Otherwise, returns the zero- based index of the alternative of the contained value.