Hi everyone.
Today i have been playing with templates and decided to make a generic question and answer function using templates to allow you to choose the return type for each call.
Code below.
template< class T >
T qAndA(const std::string Question,const T retType)
{
T retVar;
std::cout<<Question<<std::endl; //ask the question
std::cin>>retVar; //get the response
return retVar;
}
using namespace std;
int main(int argc, char* argv[])
{
string meh;
meh = qAndA("What! is your quest?: ",meh);
cout<<"you entered "<<meh<<endl;
cin.ignore(1000,'\n');
int x = 0;
x = qAndA("What is your favourite Number",x);
cout<<"you entered "<<x<<endl;
cin.ignore(1000,'\n');
char ch = 0;
ch = qAndA("What is your favourite Letter",ch);
cout<<"you entered "<<ch<<endl;
cin.ignore(1000,'\n');
return 0;
}
The thing i would like to do is that if T is a string i would like to use getline instead of cin so i can read a string with spaces in it. Also any comments of how im using templates so far would be appreciated.
I would like to make it known at this point the reason i have T in the input side is that from my understanding the template return type in this function is defined soley by the input type.
I was hoping i could do something like if( T==std::string ){ getline(cin,retVar); } but it doesn't like that idea.
Any hope appreciated thanks :)