I want to create a function that will loop until a user enters the correct input type. I'm new to using templates, but I imagine if I want to validate a general type then a template function would be the correct tool to use. I want the function to keep asking the user to enter an input until the type matches the model type.
So this is my attempt so far (which throws an error: 'input': undeclared identifier)
template <typename T>
T check_input(T model_input, string message)
{
for (;;)
{
cout << message << endl;
T input; // will it make the input type the same type as model input used in the arg?
cin >> input;
// if valid input then for loop breaks
if (cin.fail())
{
// prompts that there was an error with the input and then loops again
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input, please try again" << endl;
}
else
{
break;
}
}
return input;
}
Will having the unused model parameter, force the input variable to be of the same type? (also is this bad programming practice to have an unused parameter?)
Is there a more eligant way to write a general validation check loop?
thanks
Aucun commentaire:
Enregistrer un commentaire