Can I encourage g++ to inline a switch returning a sign?

Since in this situation, int sign(MyEnum) function it not used by other translation units, then it could be marked static.

In this context, static means that the function is local to the translation unit, and does not link outside of this translation unit. (The keyword static has different meanings in C++ depending on the context it is used.)

That allows the optimizers to perform more optimizations and possibly eliminate the function entirely (assuming optimization is enabled).


Here's an alternative take on the thing:

template <int sign>
int f(int a, int b, int c)
{
  const int x = a * b - sign * c;
  const int y = a + sign * c;

  return x / y;
}


int f(int a, int b, int c, MyEnum e)
{
  const int sign = sign(e);
  if (sign == 1) return f<1>(a, b, c);
  else return f<-1>(a, b, c);
}

This way, you keep the safety you want (in the form of the exception), but then transform the resulting information into a compile-time value which the compiler can use for optimisations.

As Chris pointed out in comments, if sign is only ever used to switch the sign of c, you can get rid of the template altogether and just flip c's sign when calling:

int f(int a, int b, int c)
{
  const int x = a * b - c;
  const int y = a + c;

  return x / y;
}


int f(int a, int b, int c, MyEnum e)
{
  const int sign = sign(e);
  if (sign == 1) return f(a, b, c);
  else return f(a, b, -c);
}