c++ - 使用 TMP 计算表示值所需的位数

标签 c++ templates template-meta-programming

我想使用模板元编程来计算表示给定数字所需的最少位数。我以前从未使用过 TMP,所以这可能是完全可笑的。

struct ValueHolder
{
   typedef float value;
};

template<struct ValueHolder>
struct logB2
{
   enum { result = (((*(int*)&ValueHolder.value & 0x7f800000) >> 23) - 127) };
};

template <struct logB2 n>
struct bits2use {

    enum { return = !((n::return > 0) && !(n::return & (n::return-1))) ? n++ : n };
};

#ifndef NUM 
#define NUM 18 
#endif

int main()
{
   std::cout << bits2use<NUM>::return << '\n';
   return 0;
}

这是我所知道的运行时代码的样子:

int ch_bits;                    //how many bits needed to send the channel
float xf = CHN_CNT;             //need a float for log2 calc
int x = CHN_CNT;

//Calculate how many bits you need for a given integer, i.e. for a 64 channels you need
//6 bits to represent 0-63 unsigned.
ch_bits = ((*(int*)&xf & 0x7f800000) >> 23) - 127;  //log_2
if( !((x > 0) && !(x & (x-1))) )                    //true if x is not a power of 2
    ch_bits ++;

最佳答案

这应该可以满足您的需求

#include <stdio.h>

template<int N> struct bits;
template<> struct bits<1> { enum { value=1 }; };
template<int N> struct bits { enum { value = 1 + bits<(N>>1)>::value }; };

int main() {
    printf("%i\n", bits<5000>::value);
    return 0;
}

关于c++ - 使用 TMP 计算表示值所需的位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24939771/

相关文章:

c++ - C++ 中的类模板和友元

c++ - 有没有办法在编译时检测是否可以使用给定的一组参数类型成功调用通用 lambda?

c++ - 代表C++类模板中的空类型

C++ Qt : catching a segfault from dll

c++ - 如何延迟成员变量的初始化

c++ - 使用 `using` 或其他方式显式实例化函数模板

c++ - 如何在编译时检测类型是否为 lambda 表达式?

c++ - 检查指向 vector C++中对象的指针

c++ - 现代 OpenGL(4.6) - 将着色器编译到库中

c++ - 具有以不同方式实现的可变参数构造函数的模板类 : What are the benefits and downfalls of each version?