你如何迭代元组?

时间:2014-09-03 02:54:00

标签: c++ c++11

我写了一些编译好的代码:

#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;
        }
    }
};

尝试使用它虽然我可以看到它实际上没有用。有没有办法使用标准库函数迭代元组?

1 个答案:

答案 0 :(得分:3)

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

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...); }
};