Tuples and std::tuple

Getting Tuple Element Types

How can I get the type of an element in a tuple?

Vector art representing computer hardware

To get the type of an element in a tuple, you can use the std::tuple_element type trait. It takes the index of the element as a template parameter and the tuple type itself. Here's an example:

#include <tuple>
#include <string>
#include <type_traits>

int main() {
  std::tuple<int, float, std::string> myTuple;

  // Get the type of the first element (index 0)
  using FirstType = std::tuple_element_t<
    0, decltype(myTuple)>;
  static_assert(std::is_same_v<FirstType, int>);

  // Get the type of the third element (index 2)
  using ThirdType = std::tuple_element_t<
    2, decltype(myTuple)>;
  static_assert(std::is_same_v<
    ThirdType, std::string>);
}

In this code:

  • std::tuple_element_t<0, decltype(myTuple)> gets the type of the element at index 0 in myTuple. It's equivalent to int.
  • Similarly, std::tuple_element_t<2, decltype(myTuple)> gets the type of the element at index 2, which is std::string.

We use static_assert with std::is_same_v to verify the types at compile-time.

The _t suffix in std::tuple_element_t is a convenience alias that saves you from writing typename std::tuple_element<...>::type.

Getting element types is useful when you need to write generic code that works with tuples. For example, you might have a function template that accepts a tuple and does different things based on the types of its elements.

Keep in mind that the element indices must be known at compile-time, as they are template parameters. If you need to access elements based on a runtime index, you'll need to use std::get instead and rely on the compiler to deduce the return type.

This Question is from the Lesson:

Tuples and std::tuple

A guide to tuples and the std::tuple container, allowing us to store objects of different types.

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Tuples and std::tuple

A guide to tuples and the std::tuple container, allowing us to store objects of different types.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved