Playing with C++0x -- tuple
Some C++0x features are already available in g++ 4.3. Others will be available in the 4.4 release -- see this page for a summary of C++0x language support in g++.
What is a tuple? It's a std::pair on steroïds: it can contain any number of elements. For the impatient, the whole sample program is available from here. It can be compiled with:g++-4.3 --std=c++0x tuple.cpp -o tuple.
Now let's see how to create a tuple:
#include <string> #include <tuple> typedef std::tuple<int, double, std::string> my_tuple_t; my_tuple_t a_tuple(1, 5.0);
Every element of the tuple gets initialized to its default value if it's not specified. Indeed displaying the third element:
std::cout << std::get<2>(a_tuple) << std::endl;
outputs nothing, because the string element was default-constructed to an empty string. The
std::make_tuple function, like std::make_pair for std::pair, can be used to create a tuple using type deduction:
std::cout << std::get<1>(std::make_tuple(false, std::string("see"))) << std::endl;
A tuple element can be changed using the same get function:
std::get<2>(a_tuple) = "a string";
Of course, a tuple is type safe. Trying to put a string at the first element:
std::get<0>(a_tuple) = "another string";
does not compile. But there's more: you also get a compilation error when trying to access an element that does not exist. For example trying to display fourth element does not compile:
std::cout << std::get<3>(a_tuple) << std::endl;
What else can you do with tuples? You can test them for equality, or assign them:
my_tuple_t another_tuple = std::make_tuple(2, 10.0, std::string("nothing"));
std::cout << (a_tuple == another_tuple) << std::endl;
another_tuple = a_tuple;
std::cout << (a_tuple == another_tuple) << std::endl;
You can also retrieve multiple elements at once, possibly ignoring some of them:
std::string a_string; std::tie(std::ignore, std::ignore, a_string) = another_tuple;
Last, you can concatenate two tuples into a new tuple:
std::tuple<int, double, std::string, bool, std::string> cat =
std::tuple_cat(a_tuple, std::make_tuple(false, std::string("see")));