lundi 30 janvier 2017

C++ std::string to number template

I am currently trying to implement my own standard input reader for personal use. I have created a method to read an integer from std input and do some checks on its validity. The idea is that I read a string from the std input, do several checks, convert to int, do last checks, return the value that has been read. If any error happens meanwhile the checks I will just fill an errorHint to print on std::cerr and return std::numeric_limits::min().

I think the idea is quite simple and straightforward to implement, now I wanted to generalise the concept and make the method template, so basically I could chose at compile time, whenever I need to read from the std input which type of integer I want (it could be int, long, long long, unsigned long and so on but an integer). In order to do so I have created the following static template method:

template<
    class T,
    class = typename std::enable_if<std::is_integral<T>::value, T>::type
> 
static T getIntegerTest(std::string& strErrorHint,
                        T nMinimumValue = std::numeric_limits<T>::min(),
                        T nMaximumValue = std::numeric_limits<T>::max());

and the implementation in the same .hpp file few lines below:

template<
    class T,
    class>
T InputReader::getIntegerTest(std::string& strErrorHint,
                              T nMinimumValue,
                              T nMaximumValue)
{
    std::string strInputString;
    std::cin >> strInputString;

    // Do several checks

    T nReturnValue = std::stoi(strInputString); /// <--- HERE!!!

    // Do other checks on the returnValue

    return nReturnValue;
}

Now the problem is, I want to convert the string that I just read and that I know is within the correct range to the integer type T. How can I do this in a good way?

Aucun commentaire:

Enregistrer un commentaire