This post will discuss how to implement a Triplet class in C++.

1. Using std::tuple

Since C++11, we can use std::tuple to hold a collection of elements in C++. It is a generalization of std::pair and is available in the standard library in the header <tuple>. It can be used to store a triplet of the same type as follows:

Download  Run Code

Output:

(1, 2, 3)

 
The std::tuple allows each element to be of a different type. We can even create a type alias for triplets:

Download  Run Code

Output:

(1, 2, 3)

2. Using custom class

Another option is to implement your Triplet class. Here’s an example of its usage using struct. The program implements a utility function to create a Triplet instance for the same element type:

Download  Run Code

Output:

(1, 2, 3)

 
Here’s an equivalent version using a class with the constructor.

Download  Run Code

Output:

(1, 2, 3)

 
We can easily extend the solution to have each element of a different type. The usage remains similar:

Download  Run Code

Output:

(1, 2, 3)

3. Using Boost.Tuple

If your project uses the boost C++ library, you can use Boost.Tuple to construct a tuple, whose elements may be of the same or different types. Boost.Tuple is designed for ease of use and efficiency and can be used before C++11.

Download Code

Output:

(1, 2, 3)

That’s all about implementing a Triplet class in C++.