Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bit shift compile error from template instantiation with float type

Tags:

c++

c++11

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

like image 235
user2746401 Avatar asked Aug 23 '26 20:08

user2746401


1 Answers

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);
}
like image 149
Jarod42 Avatar answered Aug 26 '26 12:08

Jarod42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!