Help with template function
have a problem, I want to create a function that can handle any type and react to it accordingly. So I have used a template on my function, the problem is that I am trying to tell my function that I can only fill a string with a character array if the type of the varible is a string.
Despite this it still churns out the old "error C2440: '=' : cannot convert from 'char [100]' to 'int'" message.
My code is such:
Code:
//// ********* EditField: Displays the old value of a field and allows the user to modify a fields data.
template <class T>
void EditField(T value)
{
char buffme[100];
cout << "Old: " << value << endl;
cout << "Enter new:->";
cin.getline(buffme,99);
if(typeid(value).name() == typeid(int).name()) {value = atoi(buffme); return;}
if(typeid(value).name() == typeid(string).name()) {value = buffme; return;}
if(typeid(value).name() == typeid(float).name()) {value = atof(buffme); return;}
}
Can anyone help?
Re: Help with template function
In a template function all code is compiled for each type. So each of the branches of the if statement is compiled, even if they are never executed. The solution in this case is to handle the input using an overloaded function:
Code:
parse(buffer, value);
// Interpret a string as a value of type T
void parse(const string& buffer, string& out) { out = buffer; }
void parse(const string& buffer, int& out) { out = atoi(buffer); }
//etc.
You could also use "cin >> value" directly, this function is overloaded for most common types.
Re: Help with template function
Thank you, it is as I feared. I would have to overload 3 types and repeat my code for each of them.
Re: Help with template function
Not at all, you only have to 'repeat' the bit that is different. You can call overloaded functions, and even other template functions, from a template function:
Code:
template <class T>
void EditField(T& value) {
cout << "Old: " << value << endl;
cout << "Enter new:->";
read(value);
}
template <typename T>
void read(T& value) {
cin >> value; // handles integers and floats
}
void read(string& value) {
getline(cin, value);
}
Re: Help with template function
Ah good thanks again, I am starting to regret using the string class in my program :rolleyes:. I should have used a 2D character array::duck:
Re: Help with template function
What's that got to do with anything?