Suppose I have a class Matrix5x5
(with suitably overloaded index operators) and I write a method trace
for calculating the sum of its diagonal elements:
double Matrix5x5::trace(void){
double t(0.0);
for(int i(0); i <= 4; ++i){
t += (*this)[i][i];
}
return t;
}
Of course, if I instead wrote:
return (*this)[0][0]+(*this)[1][1]+(*this)[2][2]+(*this)[3][3]+(*this)[4][4];
then I would be sure to avoid the overhead of declaring and incrementing my i
variable. But it feels quite stupid to write out all those terms!
Since my loop has a constexpr
number of terms that happens to be quite small, would a compiler inline it for me?