std::tuple遍历
遇到个需要将两个std::tuple对应元素分别求平均值的需求
实现
#include <iostream>
#include <tuple>
template <typename T, size_t S = 0, size_t E = std::tuple_size<T>::value>
void _avg(const T &t1, const T &t2, T &rs)
{
std::get<E - 1>(rs) = (std::get<E - 1>(t1) + std::get<E - 1>(t2)) / 2;
if constexpr (E - 1 > S && E - 1 > 0)
{
_avg<T, S, E - 1>(t1, t2, rs);
}
}
template <typename T, size_t S = 0, size_t E = std::tuple_size<T>::value>
T avg(const T &t1, const T &t2)
{
T rs;
_avg<T, S, E>(t1, t2, rs);
return rs;
}
// 遍历输出 tuple
template <typename T, int N, size_t S = 0, size_t E = std::tuple_size<T>::value>
void _print(const T &t)
{
std::cout << std::get<N - 1>(t) << '\t';
if constexpr (N - 1 > S && N - 1 < E)
{
_print<T, N - 1, S, E>(t);
}
}
template <typename T, int N = std::tuple_size<T>::value, size_t S = 0, size_t E = std::tuple_size<T>::value>
void print(const T &t)
{
_print<T, N, S, E>(t);
}
int main()
{
auto t1 = std::make_tuple(2, 4, 6, 8, 10, 12, 14, 16, 18, 20);
auto t2 = std::make_tuple(4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048);
auto rs = avg<decltype(t1)>(t1, t2);
print<decltype(rs), std::tuple_size<decltype(rs)>::value>(rs);
return 0;
}