,
. , ,
, .
, ScarletAmaranth, std::tuple
.
The following program shows how to get such a tuple using std::forward_as_tuple, and another way to do the repetition by compiletime recursion without an auxiliary device.
#include <tuple>
struct A
{
char ch;
int i;
double d;
};
std::tuple<char const &, int const &, double const &> get_A_vals(A const & a)
{
return std::forward_as_tuple(a.ch,a.i,a.d);
}
template<size_t I = 0, typename Func, typename ...Ts>
typename std::enable_if<I == sizeof...(Ts)>::type
for_each_in_tuple(std::tuple<Ts...> const &, Func) {}
template<size_t I = 0, typename Func, typename ...Ts>
typename std::enable_if<I < sizeof...(Ts)>::type
for_each_in_tuple(std::tuple<Ts...> const & tpl, Func func)
{
func(std::get<I>(tpl));
for_each_in_tuple<I + 1>(tpl,func);
}
template<typename Func>
void for_each_in_A(A const & a, Func func)
{
for_each_in_tuple(get_A_vals(a),func);
}
#include <iostream>
struct printer
{
template<typename T>
void operator () (T && t)
{
std::cout << t << std::endl;
}
};
int main()
{
A a{'a',1,2.0};
for_each_in_A(a,printer());
return 0;
}
Program Outputs:
a
1
2
If you have control over structures or classes whose members you need to iterate over, you might consider whether it is practical to simply drop them and use them everywhere std::tuple.
Code built with gcc 4.8.2 and 3.3 clang, -std=c++11.
source
share