我有一个元组:
std::tuple<int, std::string, bool> foo = { 10, "Hello, world!", false };
Run Code Online (Sandbox Code Playgroud)
我有一个类型的单个变量:
MyClass bar;
Run Code Online (Sandbox Code Playgroud)
我应该如何编写一个将一个值(或者甚至多个值,如果可能的话)附加到一个新元组中的泛型函数?
std::tuple<int, std::string, bool, MyClass> fooBar = tuple_append(foo, bar);
^^^^^^^^^^^^
// I need this magical function!
Run Code Online (Sandbox Code Playgroud)
hmj*_*mjd 16
使用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";
}
Run Code Online (Sandbox Code Playgroud)
输出:
10 Hello, world! 0 a
为了附加单个元素,这将起作用:
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));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8150 次 |
| 最近记录: |