Skip to main content

std::variant<Types...>::index

Declarations

C++17

constexpr std::size_t index() const noexcept;

Returns the zero-based index of the alternative that is currently held by the variant.

If the variant is valueless_by_exception, returns variant_npos.

Example

#include <variant>
#include <string>
#include <iostream>
int main()
{
std::variant<int, std::string> v = "abc";

std::cout << "v.index = " << v.index() << '\n';

v = {};

std::cout << "v.index = " << v.index() << '\n';
}
Result
v.index = 1
v.index = 0

std::variant<Types...>::index

Declarations

C++17

constexpr std::size_t index() const noexcept;

Returns the zero-based index of the alternative that is currently held by the variant.

If the variant is valueless_by_exception, returns variant_npos.

Example

#include <variant>
#include <string>
#include <iostream>
int main()
{
std::variant<int, std::string> v = "abc";

std::cout << "v.index = " << v.index() << '\n';

v = {};

std::cout << "v.index = " << v.index() << '\n';
}
Result
v.index = 1
v.index = 0