如何迭代std:tuple的元素?我如何迭代一个元组(使用C+11)?我尝试了以下几点:for(int i=0; i<std::tuple_size<T...>::value; ++i)
std::get<i>(my_tuple).do_sth();但这是行不通的:错误1:对不起,未实现:无法展开“侦听器.”到一个固定长度的参数列表中。错误2:我不能出现在常量表达式中。那么,如何正确地迭代元组的元素呢?
3 回答
慕姐8265434
TA贡献1813条经验 获得超2个赞
#include <tuple>#include <utility> #include <iostream>template<std::size_t I = 0, typename... Tp>inline typename std: :enable_if<I == sizeof...(Tp), void>::type print(std::tuple<Tp...>& t) { }template<std::size_t I = 0, typename... Tp>inline typename std::enable_if<I < sizeof...(Tp), void>::type print(std::tuple<Tp...>& t) { std::cout << std::get<I>(t) << std::endl; print<I + 1, Tp...>(t); }intmain(){ typedef std::tuple<int, float, double> T; T t = std::make_tuple(2, 3.14159F, 2345.678); print(t);}
for_each
#include <tuple>#include <utility> template<std::size_t I = 0, typename FuncT, typename... Tp>inline typename std: :enable_if<I == sizeof...(Tp), void>::type for_each(std::tuple<Tp...> &, FuncT) // Unused arguments are given no names. { }template<std::size_t I = 0, typename FuncT, typename... Tp>inline typename std::enable_if<I < sizeof...(Tp), void>::type for_each(std::tuple<Tp...>& t, FuncT f) { f(std::get<I>(t)); for_each<I + 1, FuncT, Tp...>(t, f); }
FuncT
- 3 回答
- 0 关注
- 815 浏览
添加回答
举报
0/150
提交
取消