##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# std::variant::index

From cppreference.com
< cpp‎ | utility‎ | variant

constexpr std::size_t index() const |  | (since C++17)

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

### [edit] Exceptions

`noexcept` specification:
noexcept

### [edit] Example

Run this code

    #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';
    }

Output:

    v.index = 1
    v.index = 0

### [edit] See also

holds_alternative (C++17) | checks if a given type appears exactly once in a variant (function template) [edit]
std::get(std::variant) (C++17) | reads the value of the variant given the index or the type (if the type is unique), throws on error (function template) [edit]

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=cpp/utility/variant/index&oldid=91657"
Category:

- unconditionally noexcept

Hidden categories:

- Pages with unreviewed unconditional noexcept template
- Pages with unreviewed noexcept template