A TR1 Tutorial: Class std::tr1::tuple

In a previous article, I gave a tutorial on the array class from the TR1 implementation released by Microsoft with the VC++ 2008 Feature Pack. In this article, I will talk about class tuple and the other classes and functions from the header with the same name, <tuple>.

Type tuple

A tuple is a sequence with a fixed number of elements of different types. The difference from an array is that a tuple is a heterogeneous sequence, whereas the array is a homogeneous sequence. Class tuple is a template class and is defined in the header <tuple> under the namespace std::tr1. Although theoretically a tuple can hold any number of elements (but finite), the implementation from VC++ 2008 Feature Pack only supports at most 15 elements.

Premises

In the examples from this tutorial, I will use a tuple with three elements, an int, a double, and a string. For the clarity of the samples, I will use this type definition:

typedef std::tr1::tuple<int, double, std::string> tuple_ids;

Also, I will use the following function for printing a tuple of the above type (I will provide details about accessing a tuple’s elements in a following paragraph):

void print_tuple(const std::tr1::tuple<int, double,
                 std::string>& t)
{
   std::cout << std::tr1::get<0>(t) << " "
             << std::tr1::get<1>(t) << " "
             << std::tr1::get<2>(t) << std::endl;
}

Creating tuples

The simplest way to define a tuple is by using the default constructor:

tuple_ids t;
print_tuple(t);
0 0

Another option is using the constructor with parameters:

tuple_ids t(1, 2.5, "three");
print_tuple(t);

The output is:

1 2.5 three

A third option is creating a tuple using function make_tuple from the header <tuple>.

tuple_ids t = std::tr1::make_tuple(10, 20.5, "thirty");
print_tuple(t);
10 20.5 thirty

Tuple size

For the size of a tuple (number of elements), there is another template class called tuple_size, that has a member called value that represents the size of a tuple.

std::cout << "size: " << std::tr1::tuple_size<tuple_ids>::value
   << std::endl;
size: 3

Accessing tuple elements

To access elements from a tuple, you have to use function get:

  • Reading
  • tuple_ids t(1, 2.5, "three");
    std::cout << std::tr1::get<0>(t) << " "
              << std::tr1::get<1>(t) << " "
              << std::tr1::get<2>(t) << std::endl;
    

    the output is

    1 2.5 three
  • Writing
  • tuple_ids t;
    print_tuple(t);
    
    std::tr1::get<0>(t) = 10;
    std::tr1::get<1>(t) = 20.5;
    std::tr1::get<2>(t) = "thirty";
    print_tuple(t);
    

    the output is

    0 0
    10 20.5 thirty
    

More by Author

Must Read