Briefly dismiss the fact that normal function overloading will serve this example better. It is meant only as a way to learn about template programming. Having said that, you are welcome to comment on the benefits/differences you'll get from using function overload, compared to function template specialization (although that might deserve a question of its own).
Consider the following example:
template <typename T>
inline void ToString(T value, char* target, size_t max_size );
template <>
inline void ToString<float>(float value, char* target, size_t max_size)
{
snprintf( target , max_size , "%f" , value);
}
template <>
inline void ToString<double>(double value, char* target, size_t max_size)
{
snprintf( target , max_size , "%f" , value);
}
Is there a way to write only one of these specializations that match both float
and double
types?
Basically I envision writing a template specialization for a template type that will match both float
and double
(as sort of 'float or double' type matcher) but I'm not sure whether that is possible at all with C++. That said, I've seen unexpected template magic happen in front of my eyes before, so I think it's a good question to ask here.