类型访问者在c ++中的类型链接 [英] type visitor over typelist in c++
问题描述
我正在寻找一种方法来实现类型访问者超过c ++类型串。
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
当然,每个函数应该类型串。
示例在类型串中使用sizeof和 static void T :: addCounter(int x)
(以跟踪类型使用次数)。
通常,我想对任意参数执行任何关于类型的任何'静态'操作。
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.
推荐答案
这样可能会有效:
#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> { };
现在您可以说访问< SizeVisitor,double,char,int> ;: :value 。
您可以修改此方法以接受一个单独的 tuple
)类,而不是类型列表的裸体类型,你还可以将 SizeVisitor
概括为一些任意的二进制函数,类似于 std :: accumulate
(而不是 0u
你会有蓄电池的中性元件)。
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).
这篇关于类型访问者在c ++中的类型链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!