C++ 将std::string(保证数字)强制转换为无符号字符

C++ 将std::string(保证数字)强制转换为无符号字符,c++,casting,stringstream,unsigned-char,C++,Casting,Stringstream,Unsigned Char,我创建了一个模板,用于将字符串转换为不同的数据类型,当数据类型为无符号字符时,该模板会出现问题 template<class TYPE> bool TryParse(const std::string value, TYPE &out) { std::istringstream iss(value); iss >> out; if (iss.fail()) { return false; } re

我创建了一个模板,用于将字符串转换为不同的数据类型,当数据类型为无符号字符时,该模板会出现问题

template<class TYPE>
bool TryParse(const std::string value, TYPE &out)
{
    std::istringstream iss(value);
    iss >> out;

    if (iss.fail())
    {
        return false;
    }

    return true;
}
模板
bool TryParse(const std::字符串值、类型和输出)
{
标准::istringstream iss(值);
iss>>退出;
if(iss.fail())
{
返回false;
}
返回true;
}
问题是,
istringstream
会将它看到的第一个字符视为字符,而不是将其视为数字字符串。因此,如果我传递一个值“255”,返回的值将是“2”


最好的解决方案是将
out
变量强制转换为无符号int,执行该操作,然后再次强制转换吗?

我建议使用一个重载,专门应用于
无符号char
情况,因为您需要使用中间类型

bool TryParse(const std::string & value, unsigned char & out)
{
    std::istringstream iss(value);
    unsigned int i;
    iss >> i;

    if (iss.fail()) { return false; }

    // The less-than-min check is technically redundant because both i and out
    // are unsigned, but it makes me feel better having it there.  It will become
    // necessary for the "signed char" overload, anyway.
    if (i > std::numeric_limits<unsigned char>::max() ||
        i < std::numeric_limits<unsigned char>::min()) {
            throw std::overflow_error();
            // Or you could "return false" instead, if that makes more sense.
    }

    out = static_cast<unsigned char>(i);
    return true;
}
booltryparse(const std::string和value,unsigned char和out)
{
标准::istringstream iss(值);
无符号整数i;
iss>>i;
if(iss.fail()){return false;}
//小于min的检查在技术上是多余的,因为i和out
//都没有签名,但它让我感觉更好。它会变得更好
//无论如何,“签名字符”重载是必需的。
如果(i>std::numeric_limits::max()||
i
您可以对签名字符使用几乎相同的函数。(只需将每个
未签名的
替换为
已签名的

我不建议在模板中使用中间类型,因为您需要使用尽可能广泛的类型,并且没有任何一种类型可以工作<例如,code>无符号长整型
有符号长整型
不兼容,反之亦然——而且这两种类型都与
浮点型
双精度
不兼容。有一个直接使用请求类型的基础模板,并为有问题的类型(例如,
char
)提供重载,这是正确的方法



请注意,我已将
value
参数更改为对const string的引用,因为这意味着调用方无需无故复制字符串。我也建议更改模板函数。

你可以使用<代码> Boo::ListalyOxCase——它没有解决你的特定问题,但它确实阻止了你重新发明轮子。事实上,你强迫调用者复制字符串是没有正当理由的。你为什么不为
char
添加一个专门化呢?@Deduplicator你的意思是过载,对吗?(非常不鼓励专门化功能。)@cdhowie:是吗?我知道这是相当新的,但我不知道什么是沮丧。。。