I'm using a pair of integer template parameters to specify a ratio, since I can't use a double as a template parameter. The conversion into a double is protected against divide-by-zero with a ternary. This worked in an earlier version of the compiler, but Visual Studio 2013 gives an error:
error C2124: divide or mod by zero
Here's a simplified version of the code:
template<int B1, int B2>
class MyClass
{
const double B = (B2 == 0) ? 0.0 : (double) B1 / (double) B2;
// ...
};
MyClass<0, 0> myobj;
I really want B
to be optimized out of expressions that use it when it's zero, so I need the single-line definition. I know I can just use template parameters <0, 1>
to get around it, but I wonder if there's a way to just convince the compiler that my expression is safe?
What I'm told worked:
This avoids a reliance on short circuit evaluation preventing the divide by 0; having the conditional selections happen before the division.
Original idea / Perhaps something like this...? (I think
B
should bestatic const
orconstexpr
, but I'm sure you can sort that...)If there's lots of other stuff you want in
MyClass
and don't want to duplicate or put in a base etc., you could move theB
calculation into a supporting template using the specialisation approach above.