need help! Template function specialisation in a class..
Dec 16, 2011 at 3:20pm UTC
I have this class, that has a function
str_to_T
that converts a char string to either a uint or a double. I don't know if I'm doing this right though, here is my header file so far:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
class restart {
template <class T>
T str_to_T();
};
template <typename T>
T str_to_T(const char * elem) {
// unknown type, so just throw
throw ;
}
template <>
unsigned str_to_T<unsigned >(const char * elem) {
return atoi(elem);
}
template <>
double str_to_T<double >(const char * elem) {
return atof(elem);
}
Is this the correct way of doing this?
Last edited on Dec 16, 2011 at 3:20pm UTC
Dec 16, 2011 at 3:31pm UTC
To make it work you need to make a few changes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
class restart {
public :
template <class T>
T str_to_T(const char * elem);
};
template <typename T>
T restart::str_to_T(const char * elem) {
// unknown type, so just throw
throw ;
}
template <>
unsigned restart::str_to_T<unsigned >(const char * elem) {
return atoi(elem);
}
template <>
double restart::str_to_T<double >(const char * elem) {
return atof(elem);
}
Dec 16, 2011 at 3:38pm UTC
ah of course, that makes sense, thanks :)
Topic archived. No new replies allowed.