我想要一个类型特征flatten_tuple_t,它可以从任意嵌套的元组类型中创建一个扁平的元组类型。以下代码片段说明了flatten_tuple_t.
template <typename T>
struct flatten_tuple {
using type = T;
};
// The real implementation goes here
// ...
// ...
template <typename T>
using flatten_tuple_t = typename flatten_tuple<T>::type;
// Dummy classes
struct C1 {};
struct C2 {};
struct C3 {};
struct C4 {};
struct C5 {};
struct C6 {};
int main(int argc, char* argv[]) {
static_assert(
std::is_same_v<flatten_tuple_t<std::tuple<C6, C5, std::tuple<C4, std::tuple<C3>, C2>, C1>>,
std::tuple<C6, C5, C4, C3, C2, C1>>);
static_assert(std::is_same_v<flatten_tuple_t<std::tuple<std::tuple<std::tuple<C3>, C2>, C1>>,
std::tuple<C3, C2, C1>>);
}
Run Code Online (Sandbox Code Playgroud)
Fra*_*ank 13
你可以std::tuple_cat()为你做繁重的工作。
唯一棘手的部分是必须将基本类型包装在std::tuple<>. 但是因为我们需要使用部分特化来提取类型,所以我们可以只使用基本模板而不是未定义它。
template <typename T>
struct flatten_tuple {
using type = std::tuple<T>;
};
template <typename T>
using flatten_tuple_t = typename flatten_tuple<T>::type;
template <typename... Ts>
struct flatten_tuple<std::tuple<Ts...>> {
using type = decltype(
std::tuple_cat(std::declval<flatten_tuple_t<Ts>>()...)
);
};
Run Code Online (Sandbox Code Playgroud)
如果using type = T;在基本情况下是绝对必须的,那么重命名结构flatten_tuple_helper并将其委托给它是相当简单的。
| 归档时间: |
|
| 查看次数: |
97 次 |
| 最近记录: |