再次迭代一个元组... [英] Iterating on a tuple... again
问题描述
过去一段时间我一直在做C ++,但我不熟悉模板。
It's been a while that I've been doing C++ but I'm not familiar with templates.
最近,我试图写一个类, code> std :: vector< std :: tuple< Types ...>> 。这个类必须有成员函数,我真的需要能够在元组上迭代。事实上,如果我能够打印一个元组的每个元素(按顺序),我就能够做我需要的一切。
Recently, I tried to write a class that wrap a std::vector<std::tuple<Types...>>
. This class must have member functions, and I really need to be able to iterate over the tuple. In fact, if I am able to print every element of a tuple (in the order), I would be able to do everything I need.
我发现一个解决方案使用一个演员,但我不是真的有信心,因为它是基于一个演员,我不喜欢(加上,当我尝试使用 static_cast
,它不再编译)。
I found a solution using a cast, but I'm not really confident with it since it is based on a cast that I don't really like (plus, when I try to use static_cast
, it doesn't compile anymore).
我的问题是,以下代码正确,可移植,它是一个黑客,我应该找到另一种方法来做这个比使用这个演员?此外,这个转换可能是一个运行时转换的权利?有没有办法做我想要的没有这个?
My question is, is the following code correct, portable, is it a hack and should I find another way to do this than to use this cast ? Also, this cast is probably a runtime-cast right ? Is there a way to do what I want without this ?
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;
}
预先感谢您的答复。
推荐答案
使用 <$ c
Use std::index_sequence_for
for fun and profit.
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...>());
}
EDIT : Live Demo. Thanks to @dyp. This uses an expansion trick from this answer.
这篇关于再次迭代一个元组...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!