C++ 从std::string转换为uint8

C++ 从std::string转换为uint8,c++,stdstring,C++,Stdstring,参考这里提供的漂亮解决方案, , 我想将std::string强制转换为8位数字(无符号或有符号) 问题在于,由于8位数字表示为字符,因此分析错误 (尝试解析1位以上的任何内容(如10位)失败) 有什么想法吗?将数字解析为int,然后将其转换为uint8\t。您也可以执行绑定检查。将数字解析为int,然后将其强制转换为uint8\t。您也可以执行绑定检查。使用模板专门化: template <typename T> void Convert(const std::string&

参考这里提供的漂亮解决方案, ,

我想将std::string强制转换为8位数字(无符号或有符号) 问题在于,由于8位数字表示为字符,因此分析错误
(尝试解析1位以上的任何内容(如10位)失败)


有什么想法吗?

将数字解析为
int
,然后将其转换为
uint8\t
。您也可以执行绑定检查。

将数字解析为
int
,然后将其强制转换为
uint8\t
。您也可以执行绑定检查。

使用模板专门化:

template <typename T>
void Convert(const std::string& source, T& target)
{
    target = boost::lexical_cast<T>(source);
}

template <>
void Convert(const std::string& source, int8_t& target)
{
    int value = boost::lexical_cast<int>(source);

    if(value < std::numeric_limits<int8_t>::min() || value > std::numeric_limits<int8_t>::max())
    {
        //handle error
    }
    else
    {
        target = (int8_t)value;
    }
}
模板
void转换(const std::string和source、T和target)
{
target=boost::词法转换(source);
}
模板
void转换(常量std::字符串和源、int8\u t和目标)
{
int value=boost::词法转换(源代码);
如果(值std::numeric_limits::max())
{
//处理错误
}
其他的
{
目标=(int8_t)值;
}
}

使用模板专门化:

template <typename T>
void Convert(const std::string& source, T& target)
{
    target = boost::lexical_cast<T>(source);
}

template <>
void Convert(const std::string& source, int8_t& target)
{
    int value = boost::lexical_cast<int>(source);

    if(value < std::numeric_limits<int8_t>::min() || value > std::numeric_limits<int8_t>::max())
    {
        //handle error
    }
    else
    {
        target = (int8_t)value;
    }
}
模板
void转换(const std::string和source、T和target)
{
target=boost::词法转换(source);
}
模板
void转换(常量std::字符串和源、int8\u t和目标)
{
int value=boost::词法转换(源代码);
如果(值std::numeric_limits::max())
{
//处理错误
}
其他的
{
目标=(int8_t)值;
}
}

这是我的想法。。。问题是它破坏了漂亮的模板,我试图找出是否有更优雅的解决方案,并添加到手边的点-我有接受a的模板函数-什么是排除int8的好方法?这是我的想法。。。问题是它破坏了漂亮的模板,我试图找出是否有更优雅的解决方案,并添加到手边的点上-我有一个接受a的模板函数-排除int8的好方法是什么?C++11有这些:但您仍然需要转换(即
static\u cast
)结果和检查边界。C++11有这些:但是您仍然需要转换(即
静态\u cast
)结果和检查边界。