假设我需要创建一个包含预计算的比特数(数字中的1位数目)的LUT,用于0到255的值:
int CB_LUT[256] = {0, 1, 1, 2, ... 7, 8};
如果我不想使用硬编码的值,可以使用好用的模板解决方案如何计算32位整数中设置位数的数量?
template <int BITS>
int CountBits(int val)
{
return (val & 0x1) + CountBits<BITS-1>(val >> 1);
}
template<>
int CountBits<1>(int val)
{
return val & 0x1;
}
int CB_LUT[256] = {CountBits<8>(0), CountBits<8>(1) ... CountBits<8>(255)};
这个数组在编译时完全计算出来。是否有任何方法可以避免长列表,并使用某种模板或甚至宏(抱歉!)生成此类数组,例如:
Generate(CB_LUT, 0, 255); // array declaration
...
cout << CB_LUT[255]; // should print 8
注意:这个问题不是关于计算数字中的1位数,它只是作为一个例子。我想在代码中完全生成这样的数组,而不使用外部代码生成器。数组必须在编译时生成。
编辑:为了克服编译器的限制,我找到了以下解决方案,基于Bartek Banachewicz的代码:
#define MACRO(z,n,text) CountBits<8>(n)
int CB_LUT[] = {
BOOST_PP_ENUM(128, MACRO, _)
};
#undef MACRO
#define MACRO(z,n,text) CountBits<8>(n+128)
int CB_LUT2[] = {
BOOST_PP_ENUM(128, MACRO, _)
};
#undef MACRO
for(int i = 0; i < 256; ++i) // use only CB_LUT
{
cout << CB_LUT[i] << endl;
}
我知道这可能是未定义行为...