Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <typeinfo> //for error message in inVal(T)
- using namespace std;
- /*==========================
- sum is a template function that can accept generic types and return
- the same type.
- ===========================*/
- template <class T>
- T sum(T a, T b) { return a+b; }
- /*==========================
- inVal accepts generic types by reference and performs input
- validation. I often write a function like this in my programs,
- so I thought, why not make a template out of it? It works for
- doubles and ints.
- It doesn't really work for a char. It will run,
- but it won't work as intended since anything from keyboard counts
- as a char. You could enter "DDDDDDDDDDD" and the program would
- just write the first D to the char and leave the other D's in the
- input stream.
- ===========================*/
- template <class T>
- void inVal(T &input)
- {
- cin >> input;
- while(!input)
- {
- cout << "Valid input requires " << typeid(input).name() << endl;
- cin.clear();
- cin.ignore(10,'\n');
- cin >> input;
- }
- return;
- }
- /*==========================
- Main is just for testing the functions I wrote.
- Nothing special.
- ===========================*/
- int main()
- {
- int a=1,b=3;
- double a1 = 5, b1 = 6;
- char ch;
- cout << sum(a,b);
- cout << endl << sum(a1,b1);
- inVal(a);
- inVal(a1);
- inVal(ch);
- cout << endl << a;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment