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?

1

2 Answers 2

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

that was my thinking... the problem is it ruins the pretty templating, I'm trying to figure out if there is more elegant solution
and adding to the point at hand - I have template function that accepts a <typename T> - What's a good way to exclude int8?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.