gpt4 book ai didi

c++ - 你如何遍历元组?

转载 作者:行者123 更新时间:2023-11-28 00:24:41 24 4
gpt4 key购买 nike

我写了一些这样的代码,编译得很好:

#include <tuple>

template <typename... Args>
class Functions
{
// stuff
public:
Functions(Args... args)
{
tuple<decltype(args)...> t{args...};
auto begin = begin(t);
auto end = end(t);
auto it = begin;
while (it != end)
{
cout << *it;
}
}
};

尝试使用它时,我发现它实际上不起作用。有没有一种方法可以使用标准库函数迭代元组?

最佳答案

有几种方法可以做到这一点。我喜欢的一种方法是使用这个简洁的模板扩展技巧:

auto l = {0, ((std::cout << args), 0)...};
(void)l;

优点是您不需要元组,并且与其他方法相比它相对较短。

如果你仍然需要元组,你可以使用索引通过索引访问元组元素:

template<int... Indices>
struct indices {
typedef indices<Indices..., sizeof...(Indices)> next;
};

template<int N>
struct build_indices {
typedef typename build_indices<N - 1>::type::next type;
};

template<>
struct build_indices<0> {
typedef indices<> type;
};

template<int n>
using build_indices_t = typename build_indices<n>::type;

template<typename... Args>
class Functions
{
public:
Functions(Args... args)
: Functions(std::make_tuple(args...),
build_indices_t<sizeof...(Args)>())
{ }
private:
template<typename... Ts, int... Is>
Functions(const std::tuple<Ts...>& tup, indices<Is...>)
{
print(std::get<Is>(tup)...);
}

void print() { }

template<class Head, class... Tail>
void print(Head&& head, Tail&&... tail)
{ std::cout << head; print(tail...); }
};

关于c++ - 你如何遍历元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25635503/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com