views:

102

answers:

2

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.).

+5  A: 

Implementing std::tuple is trivial given that variadic templates were introduced into the core language.

I know this is begging the question but it gives you a better search phrase to research.

Motti
+2  A: 

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:

  1. a chain of classes with head and tail elements (cons-elements)
  2. an empty tail instance to indicate the end of the list.
  3. recursive code to walk the list to a certain index, implemented as recursive template-instantiations (instantiated at compile time).

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.

DirkM