运行时类型切换类型列表作为开关,而不是嵌套的if的? [英] Runtime typeswitch for typelists as a switch instead of a nested if's?
本文介绍了运行时类型切换类型列表作为开关,而不是嵌套的if的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是来自TTL:
////////////////////////////////////////////////////////////
// run-time type switch
template <typename L, int N = 0, bool Stop=(N==length<L>::value) > struct type_switch;
template <typename L, int N, bool Stop>
struct type_switch
{
template< typename F >
void operator()( size_t i, F& f )
{
if( i == N )
{
f.operator()<typename impl::get<L,N>::type>();
}
else
{
type_switch<L, N+1> next;
next(i, f);
}
}
};
它用于类型列表上的类型切换。问题是 - 他们通过一系列嵌套的ifs做这个。有没有办法做这个类型切换作为一个单一的select语句?
It's used for typeswitching on a TypeList. Question is -- they are doing this via a series of nested if's. Is there a way to do this type switch as a single select statement instead?
谢谢!
推荐答案
你需要预处理器生成一个大的开关
。您将需要 get<>
到无操作的超限查找。检查编译器输出以确保未使用的情况不产生输出,如果你在乎;
You'll need the preprocessor to generate a big switch
. You'll need get<>
to no-op out-of-bound lookups. Check the compiler output to be sure unused cases produce no output, if you care; adjust as necessary ;v) .
查看Boost预处理程序库,如果你关心这种事情...
Check out the Boost Preprocessor Library if you care to get good at this sort of thing…
template <typename L>
struct type_switch
{
template< typename F >
void operator()( size_t i, F& f )
{
switch ( i ) {
#define CASE_N( N ) \
case (N): return f.operator()<typename impl::get<L,N>::type>();
CASE_N(0)
CASE_N(1)
CASE_N(2)
CASE_N(3) // ad nauseam.
}
};
这篇关于运行时类型切换类型列表作为开关,而不是嵌套的if的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文