使用交换机展开循环的C ++模板? [英] C++ template for unrolling a loop using a switch?

查看:156
本文介绍了使用交换机展开循环的C ++模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题类似于使用整数模板参数时可以展开循环吗?但是我想混合编译时和运行时。具体来说,我知道在编译时常数 NBLOCK ,我想在变量 start_block 上写一个开关,在运行时已知, NBLOCK 是交换机中的条目数。这是我使用宏:

My question is similar to Can one unroll a loop when working with an integer template parameter? but I want to mix compile time and runtime. Specifically, I know at compile time a constant NBLOCK and I want to write a switch on a variable start_block which is only known at runtime where NBLOCK is the number of entries in the switch. Here is what I got using macros:

#define CASE_UNROLL(i_loop)         \
  case i_loop : \
    dst.blocks[i_loop+1] -= (load_unaligned_epi8(srcblock) != zero) & block1; \
    srcblock += sizeof(*srcblock);

  switch(start_block)
    {
      CASE_UNROLL(0);
#if NBLOCKS > 2
      CASE_UNROLL(1);
#endif
#if NBLOCKS > 3
      CASE_UNROLL(2);
#endif
#if NBLOCKS > 4
      CASE_UNROLL(3);
#endif
...
...
#if NBLOCKS > 15
      CASE_UNROLL(14);
#endif
#if NBLOCKS > 16
#error "Too many blocks"
#endif
    }

我觉得很丑陋。特别是如果我想将绑定从16提高到32.

I find it very ugly. Especially if I want to raise the bound from 16 to 32.

我想知道是否可能使用一些模板元编程。硬性部分是出于性能原因,至关重要的是,切换是使用跳转表而不是嵌套条件序列编译的。

I would like to know if it is possible to write that using some template meta programming. The hard part is that for performance reasons it is crucial that the switch is compiled with a jump table than a sequence of nested conditional.

请注意,问题与 C ++ / C ++ 11 - 可变模板的切换语句?,但是据我所知,这里提出的解决方案是通过使用混合编译/ tun时间初始化函数指针数组来删除开关。我不能支付王子在这里调用一个函数。

Note that the question is very similar to C++/C++11 - Switch statement for variadic templates? but as far as I understand the solution proposed here is to remove the switch by using a mixed compile/tun time initialized functions pointer array. I can't pay the prince a calling a function here.

我正在使用GCC,如果需要一些讨厌的扩展。

I'm working with GCC if some nasty extensions is needed.

推荐答案

您可以简单地使用Boost.Preprocessor BOOST_PP_REPEAT(COUNT,MACRO,DATA)

You could simply use Boost.Preprocessor with BOOST_PP_REPEAT(COUNT, MACRO, DATA):

#define APPLY_FUNC(INDEX, FUNC) FUNC(INDEX);

// ...

switch(start_block)
{
    BOOST_PP_REPEAT(NBLOCK, APPLY_FUNC, CASE_UNROLL);
}

这应该扩展为:

switch(start_block)
{
    CASE_UNROLL(0);
    CASE_UNROLL(1);
    CASE_UNROLL(2);
    // ...
    CASE_UNROLL(NBLOCK-1);
}

这篇关于使用交换机展开循环的C ++模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆