Hands-On High Performance Programming with Qt 5
上QQ阅读APP看书,第一时间看更新

Removing branches

With this technique, we can avoid branches by generating a matching template specialization instead of executing a runtime test, as in the following example taken from the financial industry:

float calculatePrice(Party party, float value, float credit)
{
return party == Party::Buying ? value - credit : value + credit;
}

// replacement:
template<>
float Pricing<Party::Buying>::calculatePrice(float value, float credit)
{
return value - credit;
}
// the same for Party::Selling ...

We can use this technique every time when we can resolve the context (in our case, the involved party) already at compile time. So, akin to the static polymorphism technique we discussed before, this one could be called static branching.