Is there a way to check if value sent to variable is right type while it is already under that var?

Viewed 45

I couldn't find a way to check if the value that was passed into variable is right type.

For example: I have passed char into int variable and I would like to check if it is int inside int(?). I thought about checking if argument that was sent is in ascii table, but i don't find this as optimal solution. Some code:

Martice m('q');

when

Martice (int _arg) : pass(_arg) { allocation(); };

I know that I could use this method to check input:

if (std::cin.fail() == true) {
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }

but my point is to check it later, after passing it as argument.

1 Answers

If you want to distinguish between characters and integers, then you could use overloading of the Martice constructor. So you have one constructor taking an int, and one taking a char.

If you want to disallow passing of char, then you could mark the char overload as deleted:

explicit Martice(char) = delete;

If you want to allow it, but convert digit characters to numbers it's a little more complicated, as you must then use default-construction (if possible) and then convert the character and use assignment:

explicit Martice(char _arg) : Martice()  // Delegating to default constructor
{
    if (!std::isdigit(_arg))
    {
        // TODO: Not a digit, do something, perhaps throw an exception
    }
    else
    {
        pass = _arg - '0';  // Convert digit to number
        allocation();
    }
}

Note the use of explicit for the constructors. That will disallow implicit conversion from characters to Martice objects.

Related