将字符串转换为整数类型T,检查是否存在溢出

Convert string to integer type T, checking for overflow

本文关键字:检查 是否 存在 溢出 类型 字符串 转换 整数      更新时间:2023-10-16

目标是一个函数,给定一个包含数字的字符串和一个整数类型T,如果该值适合该类型而没有溢出,则返回成功+转换值,否则返回失败。

使用std::istringstream从字符串中读取数字适用于某些情况:

template<typename T>
std::pair<bool, T> decode(std::string s)
{
T value;
std::istringstream iss(s);
iss >> std::dec >> value;
return std::pair<bool, T>(!iss.fail(), value);
}
template<typename T>
void testDecode(std::string s)
{
std::pair<bool, T> result = decode<T>(s);
if (result.first)
std::cout << +result.second;
else
std::cout << "ERROR";
std::cout << std::endl;
}
int main()
{
testDecode<int32_t>("12"); // 12
testDecode<int16_t>("1000000"); // ERROR
testDecode<int16_t>("65535"); // ERROR
return 0;
}

然而,对于8位类型(因为这些类型被视为字符(,它失败了:

testDecode<uint8_t>("12"); // 49 !

负数也被错误地接受,并被解析为无符号类型:

testDecode<uint16_t>("-42"); // 65494 !

这样的功能由例如D中的std.conv.to和Rust中的str::parse提供。C++的等价物是什么?

您的解决方案看起来不错。然而,如果您想要更好的编译时优化,您应该考虑进行模板专业化。在给出的代码中,您根据类型进行分支。然而,这可能会被编译到代码中,而不是在编译时解决(在已经可能的情况下(。此外,如果您想根据类型添加额外的检查,函数很快就会变得混乱。

我写了我自己版本的转换代码,除了你的代码外,它还检查是否为整数类型提供了科学符号:

#include <type_traits>
#include <utility>
#include <string>
#include <limits>
#include <algorithm>
template <typename T>
auto to_T(const std::string &s) -> std::enable_if_t<std::is_floating_point<T>::value, std::pair<bool, T>>
{
return std::pair<bool, T>{true, T(std::stold(s))}; //read the string into the biggest floating point possible, and do a narrowing conversion
}
template <typename T>
auto to_T(const std::string &s) -> std::enable_if_t<!std::is_floating_point<T>::value && std::is_signed<T>::value, std::pair<bool, T>>
{
return ((long long)(std::numeric_limits<T>::min()) <= std::stoll(s) && //does the integer in the string fit into the types data range?
std::stoll(s) <= (long long)(std::numeric_limits<T>::max()))
? std::pair<bool, T>{true, T(std::stoll(s))}
: std::pair<bool, T>{false, 0}; //if yes, read the string into the biggest possible integer, and do a narrowing conversion
}
template <typename T>
auto to_T(const std::string &s) -> std::enable_if_t<!std::is_floating_point<T>::value && std::is_unsigned<T>::value, std::pair<bool, T>>
{
return ((unsigned long long)(std::numeric_limits<T>::min()) <= std::stoull(s) && //does the integer in the string fit into the types data range?
std::stoull(s) <= (unsigned long long)(std::numeric_limits<T>::max()))
? std::pair<bool, T>{true, T(std::stoull(s))}
: std::pair<bool, T>{false, 0}; //if yes, read the string into the biggest possible integer, and do a narrowing conversion
}
template <typename T>
auto decode(const std::string &s) -> std::enable_if_t<std::is_floating_point<T>::value, std::pair<bool, T>>
{
return s.empty() ? //is the string empty?
std::pair<bool, T>{false, 0}
: to_T<T>(s); //if not, convert the string to a floating point number
}
template <typename T>
auto decode(const std::string &s) -> std::enable_if_t<!std::is_floating_point<T>::value && std::is_signed<T>::value, std::pair<bool, T>>
{
return (s.empty() ||                                                 //is the string empty?
std::find(std::begin(s), std::end(s), '.') != std::end(s) || //or does it not fit the integer format?
std::find(std::begin(s), std::end(s), ',') != std::end(s) ||
std::find(std::begin(s), std::end(s), 'e') != std::end(s) ||
std::find(std::begin(s), std::end(s), 'E') != std::end(s))
? std::pair<bool, T>{false, 0}
: to_T<T>(s); //if not, convert the string to a signed integer value
}
template <typename T>
auto decode(const std::string &s) -> std::enable_if_t<!std::is_floating_point<T>::value && std::is_unsigned<T>::value, std::pair<bool, T>>
{
return (s.empty() ||                                                 //is the string empty?
std::find(std::begin(s), std::end(s), '.') != std::end(s) || //or does it not fit the integer format?
std::find(std::begin(s), std::end(s), ',') != std::end(s) ||
std::find(std::begin(s), std::end(s), 'e') != std::end(s) ||
std::find(std::begin(s), std::end(s), 'E') != std::end(s) ||
std::find(std::begin(s), std::end(s), '-') != std::end(s))
? //or does it have a sign?
std::pair<bool, T>{false, 0}
: to_T<T>(s); //if not, convert the string to an unsigned integer value
}

这仍然需要在平台之间进行某种程度的移植,因为std::stoldstd::stollstd::stoull可能不可用。但除此之外,它应该独立于平台类型的实现。

编辑:

我忘记了decode不应该读取数字,而是返回0的情况。现在已修复。

以下是使用istringstream并解决其注意事项的直接方法:

template<typename T>
std::pair<bool, T> decode(std::string s)
{
typedef std::pair<bool, T> Result;
if (s.empty())
return Result(false, 0);
if (!std::numeric_limits<T>::is_signed && s[0] == '-')
return Result(false, 0);
if (sizeof(T) == 1)
{
// Special case for char
std::pair<bool, short> result = decode<short>(s);
if (!result.first)
return Result(false, 0);
if (!inrange(result.second, std::numeric_limits<T>::min(), std::numeric_limits<T>::max()))
return Result(false, 0);
return Result(true, (T)result.second);
}
else
{
T value;
std::istringstream iss(s);
iss >> std::dec >> value;
return Result(!iss.fail(), value);
}
}