This page was last updated on March 13th, 2020(UTC) and it is currently May 30th, 2023(UTC).
That means this page is 3 years, 78 days, 4 hours, 5 minutes and 45 seconds old. Please keep that in mind.

35 - Function Templates Ok, now I'm going to cover some more tricky bits that will grab you when you least expect it, as well as cover a little bit of mangling. If you were an astute observer, the lack of use of extern "C" in the last lesson likely stuck "i" at the end of function names. Welcome to manging, as it's necessary for function overloading.

#include <stdio.h> //------------------------------------------------------------------------ void print(int x){ printf("%i\n", x); } //------------------------------------------------------------------------ void print(const char * x){ printf("%s\n", x); } //In C or ASM, this would be invalid! //------------------------------------------------------------------------ int inc(int x, int y = 1){ return x + y; } //------------------------------------------------------------------------ template void xchg(TYPE &x, TYPE &y){ //THIS CANNOT BE EXPORTED TYPE temp = x; x = y; y = temp; } //------------------------------------------------------------------------ extern "C" void meow(){ int x = 1, y = 2; print(100); print("MEOW!"); xchg(x, y); printf("x = %i, y = %i\n", x, y); }

You'll want to look at print() in the assembly, as well as inc. With the function beginning with "template" there's actually 2 things going on here. The first, is that when you declare "template" you're saying that you want to make a function or class (more on classes later) that can change depending on what is passed to it. The "class TYPE" says (and we can have more than one) that "TYPE" represents what it is that is going to be determined. So the function becomes "void xchg(int &x, int &y)" when the program is compiled, since we're passing INTs. The second thing we're passing is the reference. What we're actually doing is saying that we want the & value for x to be passed, not X. As a result, any time X is changed, we're actually changing the original X, where as, if you've been paying attention, X would not have been changed in main if you take them away. This subtle difference can get you in trouble, or other programmers who don't catch it. On the flip side, it might be practical, for speed concerns, to pass it that way, anyway, especially if the function never modifies the values of the parameters, since it actually has to make copies of every variable if you don't use & (for simple types, this is merely a push or a slightly higher SUB, but for classes, like we'll talk about later, this can be a realy, really big deal).

Get your own web kitty here!
©Copyright 2010-2023. All rights reserved.