0

referring to the beautiful solutions provided here, Convert string to int with bool/fail in C++,

I would like to cast a std::string to a 8 bit number (unsigned or signed) The problem is that because 8 bit number is represented as a char so it is parsed wrong
(trying to parse anything above 1 digits - like 10 - fails)

Any ideas?

Community
  • 1
  • 1
Boaz
  • 4,864
  • 12
  • 50
  • 90
  • C++11 has these: http://en.cppreference.com/w/cpp/string/basic_string/stoul but you'll still need to convert (ie `static_cast`) the result and check bounds. – rubenvb Mar 07 '12 at 13:25

2 Answers2

4

Use template specialization:

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;
    }
}
Shawnone
  • 850
  • 5
  • 17
1

Parse the number as int and then cast it to uint8_t. You may perform bound checks as well.

swegi
  • 4,046
  • 1
  • 26
  • 45
  • that was my thinking... the problem is it ruins the pretty templating, I'm trying to figure out if there is more elegant solution – Boaz Mar 07 '12 at 12:58
  • and adding to the point at hand - I have template function that accepts a - What's a good way to exclude int8? – Boaz Mar 07 '12 at 13:48