Skip to content

The tuple

July 25, 2013

The addition of variadic templates allows an arbitrary-types tuple class to be added to C++. The tuple is essentially an unnamed struct with positional arguments — its elements are accessed through their position rather than by a name. It is a generalised version of the pair class.

Firstly, it is defined in the header <tuple>. To define a tuple, simply use std::tuple with template arguments being the types that you want to be contained in the tuple.

For example, to declare a tuple whose three fields are char, int and string, you would write

typedef std::tuple<char, int, std::string> MyTuple;

To retrieve a field from a tuple, use the function std::get. It takes one template argument, which is the position to retrieve from the tuple. For example, to get the zeroth field out of a MyTuple object t, you would call

std::get<0>(t)

and its type would be char.

There is one subtlety with the tuple, which is that its constructors are explicit. The implication is that unary tuples cannot be implicitly constructed by passing a compatible parameter to a function that accepts a tuple, and a tuple cannot be constructed implicitly from an initialiser list. Therefore the following code is invalid

//does not compile, explicit tuple constructor called
std::vector<std::tuple<char, int>> foo =
  {
    {'a', 5},
    {'b', 6}
  };

There are two solutions: the first is to use typedefs, and explicitly construct your tuples; the second is to use the utility function std::make_tuple, which is like std::make_pair, in that it takes any number of arguments and returns a tuple built out of those arguments. As long as every argument is convertible to the types in your tuple then it will work.

Advertisements

From → Library, Templates

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: