liveBook · Manning

Std::get

As explained in Learn C++ by Example

std::get is a C++ standard library function template that retrieves an element from a tuple or another supported tuple-like object by index or type.

std::get retrieves an element from a tuple by compile-time index, such as std::get<0>(three_words). It also retrieves a value of a specified type from a variant. section 7.1.2 section 5.2.4

Use the form that matches the object and the information available:

  • Call std::get<index>(tuple) to retrieve a tuple element, with indexes beginning at zero. section 7.1.2
  • Call std::get<Type>(variant) after checking the active alternative with std::holds_alternative<Type>. section 5.2.4
  • Prefer structured bindings when several tuple or pair elements need names at once. section 7.1.2

Reading an extended card

After confirming that a variant does not contain Joker, retrieve its Card value with std::get<Card>(current), then pass it to the existing card-comparison function. section 5.2.4

Listing 5.30 Checking whether the guess is correct for an extended deck
bool is_guess_correct(char c,
    const std::variant<Card, Joker>& current,
    const std::variant<Card, Joker>& next)
{
    if (std::holds_alternative<Joker>(current) ||
        std::holds_alternative<Joker>(next))
        return true;                                       #1
    Card current_card = std::get<Card>(current);           #2
    Card next_card = std::get<Card>(next);                 #2
    return is_guess_correct(c, current_card, next_card);   #3
}

Inspect std::get<Card> alongside holds_alternative in the extended-deck guessing game. section 5.2.4

How Learn C++ by Example covers it

How deep it goes
Explains indexed tuple access and typed variant access with working snippets, but does not develop implementation internals.
Examples
Uses three-number tuples, tuple strings, card-or-Joker variants, and map-related structured-binding examples.
What it assumes
Assumes familiarity with basic C++ types and templates while introducing tuples, variants, and structured bindings through examples.
What you can do after
Apply it via the C++ standard library to extract tuple elements or confirmed variant alternatives.
How it connects
Connects std::get with std::tuple, std::variant, std::pair, structured bindings, and std::holds_alternative.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.