Runtime typeswitch for typelists as a switch instead of a nested if#39;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);
}
}
};
它用于在 TypeList 上进行类型切换.问题是——他们通过一系列嵌套的 if 来做到这一点.有没有办法将这种类型切换作为单个选择语句来代替?
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?
谢谢!
推荐答案
你需要预处理器来生成一个大的switch.您需要 get<> 来进行无操作越界查找.检查编译器输出以确保未使用的情况不会产生输出,如果您关心的话;根据需要进行调整;v).
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:类型列表的运行时类型开关作为开关而不是嵌套的 if?
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
