简体   繁体   English

专门用于设置整数值的模板

[英]Specialize template for set of integer values

Given a known set of integer values (1-4 in this case). 给定一组已知的整数值(在这种情况下为1-4)。

Is there any way to specialize and also call a templated function for one of these values that is nice to read and shorter than this: 有什么方法可以专门化并且还可以为这些值之一调用模板化函数,这些值很容易阅读并且比这短:

template<int level>
int function(){
  //do something
  return level;
}

void wrapper(int level)
{
  switch (level)
  {
    case 1:
      function<1>();
      break;
    case 2:
      function<2>();
      break;
    case 3:
      function<3>();
      break;
    case 4:
      function<4>();
      break;

  }
}

int main()
{
  wrapper(4);
}

You can use Boost.Preprocessor to unroll the loop for you. 您可以使用Boost.Preprocessor为您展开循环。

#include <boost/preprocessor/repetition/repeat_from_to.hpp>

template<int level>
int function() {
  //do something
  return level;
}

#define GENERATE(Z, N, _)                       \
  case N:                                       \
    function<N>();                              \
    break;

void wrapper(int level)
{
  switch ( level )
  {
    BOOST_PP_REPEAT_FROM_TO(0, 10, GENERATE, nil);
  default:
    break;
  }
}

int main()
{
  wrapper(4);
}

The preprocessed code looks like this (shortened) 预处理的代码看起来像这样(缩短)

void wrapper(int level)
{
  switch ( level )
  {
    case 0: function<0>(); break; case 1: function<1>(); break; case 2: function<2>(); break; case 3: function<3>(); break; case 4: function<4>(); break; case 5: function<5>(); break; case 6: function<6>(); break; case 7: function<7>(); break; case 8: function<8>(); break; case 9: function<9>(); break;;
  default:
    break;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM