Recently I was in a need of some sort of simple container like operations on std::tuple, things like appending or removing elements. The idea is in a way similar to many meta programming libraries already available (support for type lists and operations on them) but none of them (which I know) directly supports std::tuple’s. The closest one seems to be boost::hana library working simultaneously on types and values providing its own boost::hana::tuple for that purpose. As I wanted to learn something and also create a lightweight solution I rolled out my own library, tupac. Currently it supports two modifying algorithms: push_back and remove_if; iteration with for_each and a type-value modificator: mutate.

Modifying the tuple

Tupac comes with tupac::algo::push_back and tupac::algo::remove_if algorithms. Both of them are creating a new tuple based on provided arguments. In short:

auto t1 = std::make_tuple(3.14);
auto t2 = tupac::algo::push_back(t1, 42);

Will create a new tuple, copying original one and appending a new element, in this case 42 of type int. Resulting with a tuple<double, int>.

Similarly, tupac::algo::remove_if takes a tuple and remove elements satisfying provided predicate. Note that it operates only on types. Eg.:

auto t1 = std::make_tuple(42, 3.14);
auto t2 = tupac::algo::remove_if(t1, tupac::is_floating_point);

Will result with single element tuple.

Iterating over tuple

Sometimes you want to execute a particular piece of code on every tuple element, assuming they behave in the same way or expose certain properties. For example, having a tuple of “integer like objects” you may want to sum it up knowing only that they all support + operator. Tupac::algo::for_each is just for this purpose.

Mutating the tuple

The last one is most tricky. tupac::algo::mutate can change the type and the value of the tuple elements. For example having a tuple of int’s and unsigned int’s (std::tuple<int, int, unsigned>) you may want to transform it to a tuple of just int’s.

Pipe operator

For convenience, tupac provides a “pipe” | operator. Therefore you can chain multiple operations in one expression:

auto t = some_tuple | remove_if(is_floating_point) | push_back(42);

Will remove all floating point elements from the tuple and appends int value 42.

What is this all about?

In this blog post series I will try to show you principles behind tupac implementation, how and what was implemented along with fundamental C++ features used in the implementation. The library is built on top of the standard C++ library so you will learn pure C++ without the help of additional libraries.