gpt4 book ai didi

c++ - 检查整数类型是否适合可能不同(整数)类型的值的函数

转载 作者:IT老高 更新时间:2023-10-28 22:35:55 33 4
gpt4 key购买 nike

是否可以创建一个模板函数来检查原始数据类型是否可以适合可能不同的原始数据类型的值?让我们暂时将范围限制为整数类型。

更准确地说:是否可以创建一个“一刀切”的模板化函数,但不会收到编译器警告( bool 表达式始终为真/假、有符号/无符号比较、未使用的变量)并且没有禁用编译器警告检查?这些函数还应该在运行时限制尽可能多的检查(所有微不足道的情况都应该在编译时排除)。如果可能的话,我宁愿避免使用 C++11 等的扩展(除非存在“旧”C++ 的“快速”替换)。

注意:“值”在编译时是未知的,只有它的类型。

预期行为示例:

int main(int argc, char** argv) {
for (int i = 1; i < argc; i++) {
const int value = atoi(argv[i]);
std::cout << value << ": ";
std::cout << CanTypeFitValue<int8_t>(value) << " ";
std::cout << CanTypeFitValue<uint8_t>(value) << " ";
std::cout << CanTypeFitValue<int16_t>(value) << " ";
std::cout << CanTypeFitValue<uint16_t>(value) << " ";
std::cout << CanTypeFitValue<int32_t>(value) << " ";
std::cout << CanTypeFitValue<uint32_t>(value) << " ";
std::cout << CanTypeFitValue<int64_t>(value) << " ";
std::cout << CanTypeFitValue<uint64_t>(value) << std::endl;
}

}

输出:

./a.out 6 1203032847 2394857 -13423 9324 -192992929

6: 1 1 1 1 1 1 1 1

1203032847: 0 0 0 0 1 1 1 1

2394857: 0 0 0 0 1 1 1 1

-13423: 0 0 1 0 1 0 1 0

9324: 0 0 1 1 1 1 1 1

-192992929: 0 0 0 0 1 0 1 0

测试您的代码 herehere .

检查生成的程序集here .

这个问题的灵感来自 this post

最佳答案

使用在 stdint.h 中定义的 numeric_limits 和类型

比我的 first solution 更紧凑,同样的效率。

缺点:要包含一个额外的标题。

#include <limits>
#include <stdint.h>

using std::numeric_limits;

template <typename T, typename U>
bool CanTypeFitValue(const U value) {
const intmax_t botT = intmax_t(numeric_limits<T>::min() );
const intmax_t botU = intmax_t(numeric_limits<U>::min() );
const uintmax_t topT = uintmax_t(numeric_limits<T>::max() );
const uintmax_t topU = uintmax_t(numeric_limits<U>::max() );
return !( (botT > botU && value < static_cast<U> (botT)) || (topT < topU && value > static_cast<U> (topT)) );
}

Assembly code generated (你可以改变 T 和 U 类型)

Correctness test


注意: constexpr version写了,但显然它有一些问题。见 herehere .

关于c++ - 检查整数类型是否适合可能不同(整数)类型的值的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17224256/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com