Named tuple

Back to Data structures

A named tuple is an object which contains a fixed amount of named objects of possibly different type. A named tuple comes with an embedded hash()-function, which requires that the objects be hashable, and with equality comparison functions. The hash-function can be automatically called by the Embedded_Hash hashing object. The named tuples are generated by the macros PASTEL_NAMED_TUPLEx(), where the x is the number of contained objects. The macros take as input the name of the tuple type, and the types and names of the contained objects.

Named tuples vs C++11 tuples

While tuples are implemented generically in C++11, it is still perhaps clearer to refer to the contained objects by familiar names and syntax, rather than by std::get<Name>(tuple).

Motivation

The need for named tuples comes up in the implementation of data structures, where composite data needs to be used as a key of an associative data structure (such as std::map). For example, in LL-parsing, the applied rule is looked up based on a the current non-terminal symbol, and the current lookahead symbol. In this case a named tuple would be used as a key as follows:

PASTEL_NAMED_TUPLE2(Entry,
    Symbol, predicted,
    Symbol, lookahead);

std::unordered_map<Entry, Rule, Embedded_Hash> llParseTable;

auto iter = llParseTable.find(Entry(predicted, lookahead));

const Entry& entry = iter->first;
entry.predicted;
entry.lookahead;

This is much clearer than using std::pair (e.g. first and second), or std::tuple (e.g. std::get<Predicted>(entry)).

Files

Named tuples