C++ 找出编译时整数类型的最小/最大值的位数

C++ 找出编译时整数类型的最小/最大值的位数,c++,templates,metaprogramming,C++,Templates,Metaprogramming,是否有一种方法可以在编译时找出整数类型的最小/最大值的位数,以便将其作为模板参数放置 理想情况下,例如Boost MPL中会有一个现有的解决方案。如果失败了,我正在寻找一些手动编码解决方案的指针。这就是您要寻找的吗 std::numeric_limits<T>::digits10 std::数值限制::数字10 可以在不改变的情况下表示的位数(十进制) 可用于任何基中可以作为无符号长模板参数提供的任何值: template<unsigned B, unsigned long

是否有一种方法可以在编译时找出整数类型的最小/最大值的位数,以便将其作为模板参数放置


理想情况下,例如Boost MPL中会有一个现有的解决方案。如果失败了,我正在寻找一些手动编码解决方案的指针。

这就是您要寻找的吗

std::numeric_limits<T>::digits10
std::数值限制::数字10
可以在不改变的情况下表示的位数(十进制)


可用于任何基中可以作为无符号长模板参数提供的任何值:

template<unsigned B, unsigned long N>
struct base_digits_detail {
  enum { result = 1 + base_digits_detail<B, N/B>::result };
};
template<unsigned B>
struct base_digits_detail<B, 0> {
private:
  enum { result = 0 };

  template<unsigned, unsigned long>
  friend class base_digits_detail;
};

template<unsigned B, unsigned long N>
struct base_digits {
  enum { result = base_digits_detail<B, N>::result };
};
template<unsigned B>
struct base_digits<B, 0> {
  enum { result = 1 };
};
请注意,对于“最小/最大值的位数”,您可能需要添加1,因为
::digits10
仅表示未更改的位数。看<代码>::数字(基数2)没有该问题。
#include <climits>
#include <iostream>
int main() {
  std::cout << base_digits<10, 0>::result << '\n';
  std::cout << base_digits<10, 1>::result << '\n';
  std::cout << base_digits<10, 10>::result << '\n';
  std::cout << base_digits<10, 100>::result << '\n';
  std::cout << base_digits<10, 1000>::result << '\n';
  std::cout << base_digits<10, UINT_MAX>::result << '\n';
  std::cout << '\n';
  std::cout << base_digits<8, 0>::result << '\n';
  std::cout << base_digits<8, 01>::result << '\n';
  std::cout << base_digits<8, 010>::result << '\n';
  std::cout << base_digits<8, 0100>::result << '\n';
  std::cout << base_digits<8, 01000>::result << '\n';
  std::cout << base_digits<8, UINT_MAX>::result << '\n';

  return 0;
}
1
1
2
3
4
10

1
1
2
3
4
11