I have created a set of templates intended for unsigned integer types (e.g. uint#_t where # = 8, 16, 32, or 64).
Most of the template functions are generic. The exact same steps are carried out each time regardless of the variable type. The one thing each needs is to "know" its max value, however - so I need something to differentiate between which typename the function is being called for.
Note: in my header file, I have created a constant:
const size_t bitsperbyte = 8;
I first created another generic template to return this value, as follows:
template <typename TN> TN uint_max()
{
//Precision stores the bit precision of the passed variables
static size_t precision = bitsperbyte * sizeof(TN);
switch (precision)
{
case 8:
return UINT8_MAX;
break;
case 16:
return UINT16_MAX;
break;
case 32:
return UINT32_MAX;
break;
case 64:
return UINT64_MAX;
break;
default:
return UINT32_MAX;
break;
}
}
As far as I know this works BUT it generates a warning for each instance of the template except for uint64_t stating that precision is being lost on conversion of the larger values because it doesn't realize those conditions will never actually be true in those versions of the template.
In an attempt to rectify this, I tried to specialize this one function rather than be generic, and came up with this:
template <typename TN> uint32_t uint_max()
{
return UINT32_MAX;
}
template <> uint8_t uint_max<uint8_t>()
{
return UINT8_MAX;
}
template <> uint16_t uint_max<uint16_t>()
{
return UINT16_MAX;
}
template <> uint32_t uint_max<uint32_t>()
{
return UINT32_MAX;
}
template <> uint64_t uint_max<uint64_t>()
{
return UINT64_MAX;
}
However, this doesn't work at all, I get the following error from g++:
error: template-id 'uint_max<uint8_t>' for 'uint8_t uint_max()' does not match any template declaration
Also note: the default / generic case is just a placeholder for now, I eventually intend to change it in the precompiler based on the target machine.
So, obviously I did SOMETHING wrong there, but I'm racking my brain as to what it is. It's probably obvious. I will accept an answer that is similar to the first block but doesn't generate warnings (without just suppressing warnings!) or that fixes what I did wrong in the second block.