Silicomancer Silicomancer - 9 days ago 5
C++ Question

Exclude part of function template during compile time

Please consider the following code. It is a function template that operates on the type

T
depending from its bit width. The actual code is more complex but that is irrelevant:

template <typename T> T MyFunc(T t)
{
constexpr const uint8_t typeBitCount = sizeof(T)*8;

// more code here that works fine for all widths

if (typeBitCount >= 32)
{
if (...)
{
return t >> 16; // warning right shift count >= width of type
}

if (typeBitCount >= 64)
{
if (...)
{
return t >> 32; // warning right shift count >= width of type
}
}
}
}


I use this with 8 bit types too. In that case I get warnings (see commented lines). Unfortunately C++ isn't able to evaluate the
if
condition during compiletime even when using
constexpr
. I could probably suppress the warnings but that seems hacky to me. I would prefer to exclude the problematic code at compile time.

How can this be solved (possibly without breaking the code in pieces and without creating redundancies)?

I am using GCC 5.4.0.

Answer

I finally solved this without any templates. I used plain overloading instead. I broke the code into pieces and a single function for each type, cascading theses function from 64 bit width to 8 bit width.

Comments