Dom Bavetta
Dom Bavetta

Reputation: 104

How to passing a data type into a parameter instead of a variable

I wrote a simple input validation function to check if the user has entered the right data type and if not it'll keep asking them to re-enter until they do. Now this is something that I use a lot and in most cases I am using it on multiple data types at a time. So instead of duplicating the function and changing the data type of num inside the method is there a way I can simply just pass a data type as the parameter and have it change inside the function too?

float cinInputValidation(){
    float num;
    while(!(cin>> num)){
        cout<< "Error: Invalid Input.\n"
        << "Please try again: ";
        cin.clear();    //  Clears cin flags if user enters variable of the wrong data type.
        cin.ignore(100, '\n');  //  Ignores up to 100 characters or until a new line.
    }
    return num;
}

Now I am aware of typeof() and I have a hunch I can use it as a parameter like so

cinInputValidation(typeof(float))

but what would I do about the functions datatype itself and the type declaration of the num variable? Or is this just not possible.

Upvotes: 1

Views: 1413

Answers (1)

David G
David G

Reputation: 96810

As @chris correct pointed out, you can change cinInputValidation() into a function template so the type can be specified via a template parameter at the call site:

template<typename T>
T cinInputValidation() {
    T num;
    while (!(cin >> num)) {
        ...
    }
    return num;
}

Later on...

float f = cinInputValidation<float>();
double d = cinInputValidation<double>();

Upvotes: 4

Related Questions