迭代一个元组......再次

tfo*_*one 8 c++ templates variadic-templates c++14

我一直在做C++,但我不熟悉模板.

最近,我试着写一个包装的类std::vector<std::tuple<Types...>>.这个类必须有成员函数,我真的需要能够迭代元组.事实上,如果我能够打印元组的每个元素(按顺序),我将能够做我需要的一切.

我找到了一个使用强制转换的解决方案,但我对此并不十分自信,因为它基于我不喜欢的演员(另外,当我尝试使用static_cast它时,它不再编译).

我的问题是,以下代码是正确的,可移植的,它是一个黑客,我应该找到另一种方法来做这个比使用这个演员?此外,这个演员可能是运行时演员吗?没有这个,有没有办法做我想做的事情?

std::ostream& operator<<(std::ostream& out, std::tuple<> const& tuple)
{
    return out; // Nothing to do here
}

template<typename First, typename... Types>
std::ostream& operator<<(std::ostream& out, std::tuple<First, Types...> const& tuple)
{
    out << std::get<0>(tuple) << " ";

    // The cast that I don't like
    return out << (std::tuple<Types...>&) tuple;
}

int main()
{
    auto tuple = std::make_tuple(1, 2.3, "Hello");
    std::cout << tuple << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

提前感谢您的回答.

Pra*_*han 11

使用std::index_sequence_for的乐趣和利润.

template <typename TupleLike, size_t ... Inds>
std::ostream& PrintHelper(std::ostream& out, TupleLike const& tuple, std::index_sequence<Inds...>)
{
  int unused[] = {0, (void(out << std::get<Inds>(tuple) << " "), 0)...};
  (void)unused;
  return out;
}

template<typename... Types>
std::ostream& operator<<(std::ostream& out, std::tuple<Types...> const& tuple)
{
  return PrintHelper(out, tuple, std::index_sequence_for<Types...>());
}
Run Code Online (Sandbox Code Playgroud)

编辑:现场演示.感谢@dyp.这使用了这个答案的扩展技巧.