I'd like to know how are tuple implemented in standard library for C++0x. I tried to read description in libstdc++ manual and then read template listing, but it's really hard to understand how it works, especially when reading code.
Can someone explain me in few sentences the idea of tuple implementation? I want to know this, because I thinking about using tuples in my code and i want to understand how it works and what type of overhead does it brings (extends compile time only, perform many copy operations on memory, execute many other function in constructor, etc.).
I thought I would add a non-pseudocode simple recursive implementation for reference
Implementing
std::tuple
is possible via variadic templates, that were introduced into the core language.I know this is begging the question but it gives you a better search phrase to research.
A tuple is typically implemented as a compile time linked-list.
The code is a bit obfuscated through template-syntax, but following elements are normally present:
There exist reasonable implementations in C++03 (e.g. boost).
Variadic templates allow an unlimited number of elements, as mentioned by Motti.
The cost is normally a compile time-one. Copy constructors might be called during initialization (max 1), and when copying the tuples themselves.
One approach to implementing tuples is using multiple-inheritance. The tuple-elements are held by leaf-classes, and the tuple class itself inherits from multiple leafs. In pseudo-code:
Each leaf has an index, so that each base-class becomes unique even if the types they contain are identical, so we can access the nth element with a simple static_cast:
I've written up a detailed explanation about this "flat" tuple implementation here: C++11 tuple implementation details (Part 1)