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
Here's a standard solution idiom:
#include
#include
// Helper class
template
struct Printer
{
static typename std::enable_if::value, int>::type
print(T x, char * out, std::size_t n)
{
return std::snprintf(out, n, "%f", x);
}
};
// Convenience function wrapper
template int print(T x, char * out, std::size_t n)
{
return Printer::print(x, out, n);
}
void f()
{
char a[10];
Printer::print(1.2, a, 10); // use helper class
print(1.4f, a, 10); // wrapper deduces type for you
}
You'll get a compile-time error if you call either construction with a non-floating type. Beware though that this might erroneously work for long doubles, which require the %Lf
format specifier; and also recall that floats get promoted to doubles when passed through variadic function arguments.