Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending a value to a tuple

Tags:

c++11

I have a tuple:

std::tuple<int, std::string, bool> foo = { 10, "Hello, world!", false };

and I have a single variable of some type:

MyClass bar;

How should I go about writing a generic function that appends a single value (or even multiple values, if possible) into a new tuple?

std::tuple<int, std::string, bool, MyClass> fooBar = tuple_append(foo, bar);
                                                     ^^^^^^^^^^^^
                                            // I need this magical function!
like image 733
Hasyimi Bahrudin Avatar asked May 17 '13 07:05

Hasyimi Bahrudin


2 Answers

Use std::tuple_cat (as already commented by Zeta):

#include <iostream>
#include <string>
#include <tuple>

int main()
{
    std::tuple<int, std::string, bool> foo { 10, "Hello, world!", false };

    auto foo_ext = std::tuple_cat(foo, std::make_tuple('a'));

    std::cout << std::get<0>(foo_ext) << "\n"
              << std::get<1>(foo_ext) << "\n"
              << std::get<2>(foo_ext) << "\n"
              << std::get<3>(foo_ext) << "\n";
}

Output:

10
Hello, world!
0
a

See http://ideone.com/dMLqOu.

like image 145
hmjd Avatar answered Feb 20 '23 13:02

hmjd


For appending a single element, this will work:

template <typename NewElem, typename... TupleElem>
std::tuple<TupleElem..., NewElem> tuple_append(const std::tuple<TupleElem...> &tup, const NewElem &el) {
    return std::tuple_cat(tup, std::make_tuple(el));
}

Live example

like image 38
Angew is no longer proud of SO Avatar answered Feb 20 '23 15:02

Angew is no longer proud of SO