Tuples and std::tuple

Converting a Tuple to a Custom Type

Is there a way to convert a tuple to a custom struct or class?

Vector art representing computer hardware

Yes, you can convert a tuple to a custom struct or class using std::apply in combination with a constructor. Here's an example:

#include <string>
#include <tuple>

struct Player {
  std::string name;
  int score;

  Player(const std::string& n, int s)
    : name(n), score(s) {}
};

int main() {
  std::tuple<std::string, int> playerTuple{
    "Alice", 100};

  // Convert to Player using a constructor
  Player p = std::apply(
    [](const std::string& name, int score) {
      return Player{name, score};
    },
    playerTuple);
}

In this code:

  1. We define a Player struct with name and score members, and a constructor that takes the name and score as arguments.
  2. We have a tuple playerTuple that contains the name and score values.
  3. To convert the tuple to a Player, we use std::apply with a lambda that takes the tuple elements as separate arguments and passes them to the Player constructor.

The std::apply function takes a callable (such as a lambda or a function object) and a tuple, unpacks the tuple elements, and passes them as arguments to the callable.

In this example, the lambda takes the name and score directly as arguments (rather than capturing them as a parameter pack), and uses them to construct a Player object.

This approach allows you to convert a tuple to a custom type, which can be useful when you have a function that returns a tuple but you want to work with a more meaningful type in the rest of your code.

Keep in mind that the tuple elements must match the order and types of the constructor parameters for this to work correctly. If there's a mismatch, you'll get a compilation error.

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