I have some code that looks like:
template<unsigned int A, unsigned int B> int foo() { int v = 1; const int x = A - B; if (x > 0) { v = v << x; } bar(v); }
gcc will complain about x being negative for certain instantiations of A, B; however, I do perform a check to make sure it is non-negative. What’s the best way around this? I know I can cast x to be unsigned int but that will cause warnings about x being larger than the width of v (since it is casting a negative number to be positive). I know there is a work-around that involves creating a new templatized shift function, but I’d like to avoid that if possible.
Since A and B are known at compile time, not only can you get rid of your warning, but you can also get rid of a runtime
if, without any casts, like this: