orbitcowboy wrote:You are partially right. I know some older compilers do not support templates. But if look at the code, and you know a bit about templates, you see that the recursion is executed at compiletime, not at runntime! Its obvious, that this function is more efficient.
Among the compilers that supported templates I think a lot did not manage the overloading of a template by a specific alternate definition for a given value of the generic type.
The template instances are built at compile time but without strong optimisation you will get a sort-of recursion at execution time. Without the optimisation the compiler will generate:
Code: Select all
template <> void vByteToBits<8>(int &number, unsigned short *bits)
{
bits[7] = number & 1;
number >>= 1;
vByteToBits<7>(number,bits);
}
template <> void vByteToBits<7>(int &number, unsigned short *bits)
{
bits[6] = number & 1;
number >>= 1;
vByteToBits<6>(number,bits);
}
template <> void vByteToBits<6>(int &number, unsigned short *bits)
{
bits[5] = number & 1;
number >>= 1;
vByteToBits<5>(number,bits);
}
template <> void vByteToBits<5>(int &number, unsigned short *bits)
{
bits[4] = number & 1;
number >>= 1;
vByteToBits<4>(number,bits);
}
template <> void vByteToBits<4>(int &number, unsigned short *bits)
{
bits[3] = number & 1;
number >>= 1;
vByteToBits<3>(number,bits);
}
template <> void vByteToBits<3>(int &number, unsigned short *bits)
{
bits[2] = number & 1;
number >>= 1;
vByteToBits<2>(number,bits);
}
template <> void vByteToBits<2>(int &number, unsigned short *bits)
{
bits[1] = number & 1;
number >>= 1;
vByteToBits<1>(number,bits);
}
template <> void vByteToBits<1>(int &number, unsigned short *bits)
{
bits[0] = number & 1;
number >>= 1;
vByteToBits<0>(number,bits);
}
template <> void vByteToBits<0>(int &, unsigned short *){}
This gives a lot of code and long execution time.
I can tell you after having worked on a project having replaced a lot of variability at execution time (polymorphism) by a variability at compile time (genericity) that this principle has been dumped for the next projects. This is too complex to manage (design, make, debug, maintain) and the little performance improvement is lost in executable size that has a negative impact on program start time and page faults at execution.
Templates may be a good solution if you want to write code that nobody can understand/maintain/modify but you.