Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::get: tuple-like or variant element access

std::get selects an element by constant index or unique type and returns a reference that preserves value category and constness.

Version: C++23

Syntax

template<std::size_t I, class... Types>
constexpr decltype(auto) std::get(std::tuple<Types...>& t); // cv/ref overloads

template<class T, class... Types>
constexpr decltype(auto) std::get(std::tuple<Types...>& t); // cv/ref overloads

// Corresponding overload families exist for std::pair, std::array, and std::variant.

std::get<I> has overload families for std::tuple, std::pair, std::array, and std::variant; std::get<T> applies to tuple, pair, and variant when T occurs exactly once. The zero-based index is a compile-time constant. The result is a reference: an lvalue yields T& or const T&, while an rvalue yields the corresponding rvalue reference.

The example reads index 0 and type std::string from the tuple, then std::string from the active variant alternative, so it prints 7 blue ready. Assigning through a reference returned from a non-const tuple would modify the stored element; no copy is made.

An out-of-range index or a type that does not occur exactly once is a compile-time error. For std::variant, an otherwise well-formed get<I>/get<T> throws std::bad_variant_access when another alternative is active. If mismatch is ordinary control flow, use std::get_if or std::holds_alternative. Never retain the returned reference beyond the source object lifetime.

Examples

#include <iostream>
#include <string>
#include <tuple>
#include <variant>

int main() {
    std::tuple<int, std::string> row{7, "blue"};
    std::variant<int, std::string> state = std::string{"ready"};

    std::cout << std::get<0>(row) << ' '
              << std::get<std::string>(row) << ' '
              << std::get<std::string>(state) << '\n';
}

Result

7 blue ready

std::get → 7 blue ready

Sources