c++ - 类型列表的运行时类型开关作为开关而不是嵌套的 if's?

标签 c++ switch-statement typelist

这是来自 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 来做到这一点的。有没有办法将这种类型切换作为单个选择语句来代替?

谢谢!

最佳答案

你需要预处理器来生成一个大的 switch .你需要 get<>到无操作越界查找。检查编译器输出以确保未使用的情况不会产生输出,如果你关心的话;根据需要调整 ;v) .

如果您想擅长这类事情,请查看 Boost 预处理器库……

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.
      }
  };

关于c++ - 类型列表的运行时类型开关作为开关而不是嵌套的 if's?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2157149/

相关文章:

c++ - 终止在无限循环中运行的 std::thread

c++ - 如何在类中使用成员函数特化?

c++ - unordered_map::find with key std::pair of pointers with custom hash crashes in VS2012

c++ - 避免虚函数的标准方法

C++:向元组添加元素

c++ - 将可变参数模板内容转储到二维数组

c++ - 在 C++ 中调整数组大小时如何修复错误?

ios - Swift 元组开关案例 : pattern of type cannot match values of type

android - 如何在 Android Switch 中添加第三状态?

java - 拖放开关盒,无法访问代码?