【发布时间】:2016-01-10 06:17:30
【问题描述】:
我有一个 Boos.Hana 序列,我想将它打印到屏幕上,用逗号分隔。但是逗号仅分隔元素,所以我必须检查我是否在最后一个元素。
目前我的 hack 非常糟糕(查看指针并转换为 void*。
template<class P, class... Ts>
decltype(auto) operator<<(
std::ostream& os,
boost::hana::tuple<Ts...> const& tpl
){
os << "{";
boost::hana::for_each(
tpl, [&](auto& x){
os << x;
if((void*)&boost::hana::back(tpl) != (void*)&x) os << ", ";
}
);
return os << "}";
}
对于 Boost.Fusion,它更复杂,因为我使用了融合迭代器(boost::fusion::begin 和 boost::fusion::end),但至少我可以比较迭代器。 (bool last = result_of::equal_to<typename result_of::next<First>::type, Last>::value)。
问这个问题的另一种方法是 Hana 中是否有(元)迭代器。
【问题讨论】:
-
我不是图书馆方面的专家,但我认为你可以使用
front/drop_front(或drop_back/back)来实现你想要的。 -
谢谢。不过应该有更好的方法。如果
drop_back复制,文档中并不清楚。另外我必须更改为auto const& x但可以。boost::hana::for_each(boost::hana::drop_back(tpl), [&](auto const& x){p << x << ", "});。有趣的是,Hana 有Iterable的概念,但没有iterators。
标签: c++ boost boost-fusion boost-hana