type visitor over typelist in c++
Question
I'm looking for a way to implement 'type' visitor over c++ typelist. Here, I meant type visitor as to execute particular operator (such as sizeof) over types in typelist.
Conceptually what I want to do is:
typedef TYPELIST_3(bool, int, double) tl;
size_t tl_size = TL_sum_size<tl>(); // 13 = 1+4+8
size_t tl_min_size = TL_min_size<tl>(); // 1
size_t tl_max_size = TL_max_size<tl>(); // 8
vector<size_t> tl_sizes = TL_list_size<tl>(); // {1, 4, 8}
TL_AddCounter<tl>(3); // Call AddCounter(3) for each type in typelist
Of course, each function should be templetized over typelist.
The example uses sizeof, and static void T::addCounter(int x)
in the typelist (to track how many time that type is used).
Generically, I want to execute any arbitrary 'static' operation about type with arbitrary parameters.
Well, first of all, is any of functions above possible? if yes, how can I do? I am not sure how to iterate through typelist.
Solution
Something like this might work:
#include <type_traits>
template <typename T>
struct SizeVisitor : std::integral_constant<unsigned int, sizeof(T)> { };
template <template <typename> class Visitor, typename ...Args> struct Visit;
template <template <typename> class Visitor, typename T, typename ...Rest>
struct Visit<Visitor, T, Rest...> : std::integral_constant<unsigned int,
Visitor<T>::value + Vist<Visitor, Rest...>::value> { };
template <template <typename> class Visitor>
struct Visit<Visitor, T> : std::integral_constant<unsigned int, 0U> { };
Now you can say Visit<SizeVisitor, double, char, int>::value
.
You can modify this approach to take a single (say tuple
) class instead of the naked types for the type list, and you can also generalize the SizeVisitor
into some arbitrary binary functor, akin to std::accumulate
(and instead of 0u
you'd have the accumulator's neutral element).