17

我有一个元组:

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

我有某种类型的单个变量:

MyClass bar;

我应该如何编写一个将单个值(或者甚至多个值,如果可能的话)附加到新元组中的通用函数?

std::tuple<int, std::string, bool, MyClass> fooBar = tuple_append(foo, bar);
                                                     ^^^^^^^^^^^^
                                            // I need this magical function!
4

2 回答 2

24

使用std::tuple_cat(如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";
}

输出:

10
你好世界!
0
一个

请参阅http://ideone.com/dMLqOu

于 2013-05-17T08:08:40.737 回答
7

对于附加单个元素,这将起作用:

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));
}

活生生的例子

于 2013-05-17T08:09:16.887 回答