According to answers to that question: Which, if any, C++ compilers do tail-recursion optimization? it seems, that compiler should do tail-recursion optimization.
But I've tried proposed options and it seems that compiler can't do this optimization in case of template functions. Could it be fixed somehow?
I don't use the MS compilers, but GCC can certainly do tail-recursion optimisation for templates. Given this function:
The code produced is:
You can see that the recursive call has been turned into a jump back to the start of the function. This optimisation is only performed by GCC if the code is compiled with optimisations enabled (-O2 in this case) - perhaps the same is true for MS C++?
I'm guessing here, but it might be possible to do them manually.
The first fill template uses recursion to fill a buffer. The second uses a hand crafted tail recursion to do the same thing.
This may be bad for some reason, so I am suggesting it's use with caution.
eg.
Edit:
Good idea to add the assembler. I have changed some labels to make it clearer.
I simply used
g++ file.cpp
to compile andg++ -S file.cpp
to get the assembler.The Llvm project is a framework to create compilers which has an extensive set of optimization mechanism (tail call optimization among them). It provides c and c++ compilers, although c++ is not considered complete.