I've got a templated function that operates on either floats or (unsigned) integer types like this:
template< typename T >
void typedFunc( T& data )
{
// .... lots of code ....
if( std::numeric_limits<T>::is_integer )
{
data = data << 8;
// .... do some processing ....
}
else
{
// .... do some slightly different processing ....
}
// .... lots more code ....
}
When I use the function for floating point types I get a compile error from the bit shift as you can't bit shift a float. For a float this bit of code never executes and (hopefully) is optimized away so just needs to compile. I can get rid of the compile error by casting data to, say, an int but that changes the behaviour of the function when used with integer types.
How can I get this code to compile without changing its behaviour?
TIA
You may split your method and specialize the non common part:
template< typename T >
void preTypedFunc( T& data )
{
// .... lots of code ....
}
template< typename T >
std::enable_if_t<std::numeric_limits<T>::is_integer>
midTypedFunc( T& data )
{
data = data << 8;
// .... do some processing ....
}
template< typename T >
std::enable_if_t<!std::numeric_limits<T>::is_integer>
midTypedFunc( T& data )
{
// .... do some slightly different processing ....
}
template< typename T >
void postTypedFunc( T& data )
{
// .... lots more code ....
}
template< typename T >
void typedFunc( T& data )
{
preTypedFunc(data);
midTypedFunc(data);
postTypedFunc(data);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With