这个问题也被标记为 C++,所以这里是像我这样的模板元编程爱好者的解决方案。
要求
- 类型列表类型,此处命名为
list。
- 类似 Haskell 的
filter 元函数。
-
head 元函数,用于获取类型列表的第一个元素。
代码
此解决方案自动执行已接受的解决方案(即“转到stdint.h 并选择最适合您的解决方案”)。那项工作可以由编译器完成,不是吗?
首先列出在<cstdint> 声明的所有特定于平台的最快整数类型:
using integer_types = list<std::int_fast8_t,std::int_fast16_t,
std::int_fast32_t,std::int_fast64_t>;
请注意,列表是按整数大小递增排序的。
现在定义一个过滤谓词。在我们的例子中,大小应该小于用户指定的大小(命名为SIZE):
template<typename T>
using f = std::integral_constant<bool,sizeof(T)*CHAR_BITS <= SIZE>;
然后过滤整数类型列表,得到结果的第一个元素:
using best_integer_t = head<filter<f,integer_types>>;
总结解决方案
template<std::size_t SIZE>
struct fastest_integer_impl
{
//Guard for the case the user specified less than one byte size:
static constexpr const std::size_t size = SIZE >= CHAR_BITS ? size : CHAR_BITS;
using integer_types = list<std::int_fast8_t,std::int_fast16_t,
std::int_fast32_t,std::int_fast64_t>;
template<typename T>
using f = std::integral_constant<bool,sizeof(T)*CHAR_BITS <= size>;
using type = head<filter<f,integer_types>>;
};
template<std::size_t SIZE>
using fastest_integer = typename fastest_integer_impl<SIZE>::type;