Consider the useful code by Zaita posted at cplusplus.com, in particular the part which gets numbers safely, modified to be a function in my case:
int get_number()
{
/**
* cplusplus.com/forum/articles/6046
* gets number from input stream
**/
string input = "";
int number = 0;
while (true)
{
getline(cin, input);
stringstream checks(input);
if (checks >> number)
return number;
cout << "Please enter a valid number\n";
}
}
Now, my question is this: Can I remove the int on the first line of the function definition for get_number(), and declare it at the top of my code with all the types I might want to return such as doing some declarations like this:
double get_number();
int get_number();
long get_number();
unsigned short get_number();
...
...
And somehow get it to do different returns depending on the variable I want to store the return from the function with? Currently I simply writing multiple definitions of essentially the same function while changing the name to get_someType
I am hoping I can do something like declare with this sort of syntax:
int get_number(int);
double get_double(double);
...
...
And my desire would be to do something like:
int x;
x = get_number(int);
I am sure this will NOT work however! Because it would be impossible to define the function’s source code with parameters with no names…
You’re looking for function
templates!This code is buggy (please don’t use cplusplus.com as a reference), since it doesn’t check that input from
std::cinis received.A templated example would look something like this (untested):
To incorporate my comment below into this answer… In a class template or function template,
typenamecan be used as an alternative toclassto declare templated types. I prefertypenamebecause we’re dealing with POD-types and notclasses.