// if I know that in_x will never be bigger than Max
template <unsigned Max>
void foo(unsigned in_x)
{
unsigned cap = Max;
// I can tell the compiler this loop will never run more than log(Max) times
for (; cap != 0 && in_x != 0; cap >>= 1, in_x >>= 1)
{
}
}
如上代码所示,我的猜测是,如果我只是写
for (; in_x != 0; in_x >>= 1)
编译器不会展开循环,因为它不能确定最大可能的 in_x。
我想知道我是对还是错,以及是否有更好的方法来处理这些事情。
或者问题可以概括为好像可以编写一些代码来告诉编译器某个运行时值的范围,而这样的代码不一定被编译成运行时二进制文件。
真的,和编译器打架 XD
// with MSC
// if no __forceinline here, unrolling is ok, but the function will not be inlined
// if I add __forceinline here, lol, the entire loop is unrolled (or should I say the tree is expanded)...
// compiler freezes when Max is something like 1024
template <int Max>
__forceinline void find(int **in_a, int in_size, int in_key)
{
if (in_size == 0)
{
return;
}
if (Max == 0)
{
return;
}
{
int m = in_size / 2;
if ((*in_a)[m] >= in_key)
{
find<Max / 2>(in_a, m, in_key);
}
else
{
*in_a = *in_a + m + 1;
find<Max - Max / 2 - 1>(in_a, in_size - (m + 1), in_key);
}
}
}