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!
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With