jeudi 5 octobre 2017

error unary minus operator applied to unsigned type results in unsigned

I currently have a function in my code that converts numeric types to strings.Due to reasons I did not use std::to_string. Now this code build fine on XCode but window seems to be complaining. The reason windows is complaining is because at one point I am passing an unsigned type and then doing a negative on it still keeps it positive as the type is unsigned. My question is can I put an if class to check if the type is signed and then enter the condition ? Will that fix the problem

    template<typename t>
    std::string MyFunct(t num,int base=10)
    {
        char str [sizeof(t)*8+1];
        int i = 0;
        bool isNegative = false;


        if (num == 0)
        {
            str[i++] = '0';
            str[i] = '\0';
            return str;
        }

        //Negative only when base is 10
        if (num < 0 && base == 10)
        {
            isNegative = true;
            num = -num; //<------ERROR in case the type is unsigned
        }
        ....
        ....
    }

How can i fix this ? Is there a way for me to tell the compiler only if the type is unsigned go in here?

Aucun commentaire:

Enregistrer un commentaire