c++ - 为元组实现创建索引序列

标签 c++ tuples

假设我想实现类似 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++ - 为元组实现创建索引序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55304672/

相关文章:

C++11 std::tuple 到 std::array 转换导致可变参数模板崩溃

python - "Too many fields to unpack"错误,即使我在左侧和右侧获得了相同数量的字段

python - 如果元组中的 string1 或 string2

c++ - 将代码从 C++ 转换为 C : `a+b > b+a` where a and b are `string`

c++ - 将 STL 容器传递给 C 函数的指南

c++ - 二维区域的内存布局

python - 列表理解从元组列表中提取多个字段

c++ - 哪些存储类型不完整的 STL 数据结构可以用作类成员?

c++ - 如何获得指向 shared_ptr 的指针?

c++ - 检测元组中的引用类型