candyapplecorn

Input Validation for Generic Types Using a Template Function

Dec 20th, 2013
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.41 KB | None | 0 0
  1. #include <iostream>
  2. #include <typeinfo> //for error message in inVal(T)
  3. using namespace std;
  4.  
  5. /*==========================
  6. sum is a template function that can accept generic types and return
  7. the same type.
  8. ===========================*/
  9. template <class T>
  10. T sum(T a, T b) { return a+b; }
  11.  
  12. /*==========================
  13. inVal accepts generic types by reference and performs input
  14. validation. I often write a function like this in my programs,
  15. so I thought, why not make a template out of it? It works for
  16. doubles and ints.
  17. It doesn't really work for a char. It will run,
  18. but it won't work as intended since anything from keyboard counts
  19. as a char. You could enter "DDDDDDDDDDD" and the program would
  20. just write the first D to the char and leave the other D's in the
  21. input stream.
  22. ===========================*/
  23. template <class T>
  24. void inVal(T &input)
  25. {
  26.     cin >> input;
  27.     while(!input)
  28.     {
  29.         cout << "Valid input requires " << typeid(input).name() << endl;
  30.         cin.clear();
  31.         cin.ignore(10,'\n');
  32.         cin >> input;
  33.     }
  34.     return;
  35. }
  36. /*==========================
  37. Main is just for testing the functions I wrote.
  38. Nothing special.
  39. ===========================*/
  40. int main()
  41. {
  42.     int a=1,b=3;
  43.     double a1 = 5, b1 = 6;
  44.     char ch;
  45.     cout << sum(a,b);
  46.     cout << endl << sum(a1,b1);
  47.     inVal(a);
  48.     inVal(a1);
  49.     inVal(ch);
  50.     cout << endl << a;
  51.     return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment