I want something in C++ that lets me do efficient integer division with specified rounding behavior, something like this:
div_down(-4,3) ==> -2
div_up(4,3) ==> 2
div_to_zero(-4,3) ==> -1
div_to_nearest(5,3) ==> 2
I'd like it to detect target machine behavior at compile time and generate the appropriate optimal implementations. Something similar for modulus would also be nice, abstracting out the undefined behavior for negative operands at compile time.
Does this exist?
If not, what's a nice way to make it? I can think of a few possible approaches:
- Try to implement them as single expressions that statically optimize
- Use constant expressions to detect target behavior and choose from multiple implementations, parhaps using templates (but how exactly?)