为元组实现创建索引序列
Making an index sequence for tuple implementation
假设我想实现类似std::tuple
的东西,只是基础知识。我想先展示一次失败的尝试。
#include <utility>
#include <iostream>
template <std::size_t I>
struct tuple_index_leaf {
using Index = std::integral_constant<std::size_t, I>;
std::size_t i = Index::value;
};
template <std::size_t... Is>
struct tuple_index : tuple_index_leaf<Is>...
{};
template <std::size_t I, std::size_t... Is>
constexpr auto get_index(tuple_index<Is...> const &i) {
return static_cast<const tuple_index_leaf<I>*>(&i)->i;
}
template <std::size_t I, typename T>
struct tuple_leaf : tuple_index_leaf<I> {
T elem;
};
template<typename... Ts>
struct tuple : tuple_leaf<sizeof...(Ts), Ts>... {
};
template <std::size_t I, typename... Ts>
auto& get(tuple<Ts...> &t) {
return static_cast<tuple_leaf<I, float>*>(&t)->elem;
}
int main() {
tuple_index<0, 1, 2> ti;
std::cout << get_index<0>(ti) << "n";
tuple<int, float> t;
get<2>(t) = 3.14;
}
现在,看看get
函数。我对最后一个类型float
进行了硬编码,我只能用索引 2 调用它,就像get<2>
一样。这是因为我的tuple
构造函数存在缺陷。如果你看那里,你会发现我正在sizeof...(Ts)
传递给tuple_leaf
.例如,在这种情况下,我所有的元组叶子都像tuple_leaf<2, int>, tuple_leaf<2, float>
。我想要的是像tuple_leaf<0, int>, tuple_leaf<1, float>...
这样的扩展。我知道,我使用的扩展tuple_leaf<sizeof...(Ts), Ts>...
没有给我这些。我需要某种索引序列,我想并开始实现类似tuple_index
.但是那个需要我通过std::size_t...
,我不知道该怎么做。所以问题是,我怎样才能获得像tuple_leaf<0, int>, tuple_leaf<1, float>...
这样的扩展?
这并不难。这里有一个例子是如何做到这一点的(不是声称唯一的方法,这是我快速整理的东西):
#include <utility>
#include <cstddef>
template <std::size_t I, typename T>
struct tuple_leaf {
T elem;
};
template<class SEQ, class... TYPE> struct tuple_impl;
template<size_t... Ix, class... TYPE>
struct tuple_impl<std::index_sequence<Ix...>, TYPE...> : tuple_leaf<Ix, TYPE>... { };
template<typename... Ts>
struct tuple : tuple_impl<std::make_index_sequence<sizeof...(Ts)>, Ts...> { };
// below lines are for testing
tuple<int, double, char*> tup;
// the fact that this compiles tells us char* has index 2
auto& z = static_cast<tuple_leaf<2, char*>&>(tup);
相关文章:
- 如何为圆环创建索引
- 从容器创建一系列索引的最惯用方法是什么?
- 在C++中从距离矩阵创建索引向量的最快方法
- 是否可以创建带有索引但没有指针的单个链表?
- 创建一个没有指针但有索引的链表
- Rust 在索引时是否隐式创建映射条目,例如C++
- 需要为SQLite3数据库创建索引(索引)
- 有没有办法创建一个花哨的迭代器和相应的新数组,以便检查每个索引的索引值的条件?
- C++向量元组,请按索引从元素创建元组
- 从 1 中创建新的字符 * 作为参数,元素位于 2 个索引之间
- 尝试在字符串中索引字符并创建新字符串
- 为元组实现创建索引序列
- 创建按顺序索引的有序映射
- 如何创建辅助数据结构来跟踪 c++ 中 decrease_key 操作的堆索引
- 从对象创建矢量包装器,该对象只允许使用索引访问向量
- 如何在编译时从两个索引序列创建一个数组
- 为对象指针数组的每个空索引创建新对象
- 如何创建一个 std::tuple,其中包含由索引元组指定的向量中的成员
- 如何从顶点/索引缓冲区创建 CGAL Nef_polyhedron_3
- 使用索引创建类的对象