I am trying to implement C++ function using assembly code -- ARMv7-a, to be specific. Now I encounter a program that I don't know how C++ function template should be implemented in assembly. I try to compile the source code with -S -O1 flag to see the generated assembly but couldn't understand it. Can any one give me a brief idea how the C++ template is translated into assembly code? Just use the following simple function as an example:
template<typename T>
T f(T a) {
return a + 1;
}
If you found any other function is easier to do the explain, please do so. Thanks!
It would help, to phrase it correctly. It's not template function, it's function template ... noticed the difference?
A template, is to generate code upon instantiation. So in this case, if you instantiate your f
for int
the assembly would be identical with
int f(int a) { // Note that having a return type void is wrong here
return a + 1;
}
There's lack of binary code generation for non instantiated templates. That's why lots of errors in template code remain dormant until instantiation for the problematic types is performed.
So for a real example, here are the 2 versions, one generated out of a function template and one out of a function (both for int
); if it wasn't for the hint at the right one couldn't tell the differene:
f2(1);
00BA25BE push 1
00BA25C0 call f2<int> (0BA12F3h)
00BA25C5 add esp,4
f(1);
00BA25C8 push 1
00BA25CA call f (0BA12EEh)
00BA25CF add esp,4
More on templates (types this time) and binary code representation here
You should implement each instance of the template in separate assembly.
Fundamentally, each template instance is a different type. You'll also need to deal with specialisations; partial or otherwise.
(Of course that means that you need to know in advance which set of T
s you need, but that is essentially what a C++ compiler does.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With