|
|
RetroX
|
|
Reply #62 Posted on: January 26, 2010, 02:56:25 pm |
|
|
Master of all things Linux
Location: US Joined: Apr 2008
Posts: 1055
|
Well, you could have this
int sum(Array<int>* numbers){ int result = 0; for(int i = 0; i < numbers->getLength();++i){ result += numbers[i]; } return result; }
int main(){ StaticArray<int, 10> array1; StaticArray<int, 20> array2; printf("%d\n", sum(&array1) + sum(&array2)); return 0; }
Also this: template<class T,int size> int sum(array<T,size> numbers) { ... } EDIT: Rusky, it's not really any more or less efficient. If anything, a template uses less space. And, it's usually a bit cleaner, sometimes.
|
|
|
Logged
|
My Box: Phenom II 3.4GHz X4 | ASUS ATI RadeonHD 5770, 1GB GDDR5 RAM | 1x4GB DDR3 SRAM | Arch Linux, x86_64 (Cube) / Windows 7 x64 (Blob)Why do all the pro-Microsoft people have troll avatars?
|
|
|
|
|
|
|
|
|
|
|
|
Josh @ Dreamland
|
|
Reply #72 Posted on: January 28, 2010, 08:02:06 pm |
|
|
Prince of all Goldfish
Location: Pittsburgh, PA, USA Joined: Feb 2008
Posts: 2950
|
Quite the opposite. Templates (in theory) save lines of code, but increase actual executable size (disk and memory) due to the fact that the code is copied with only slight modification for each instantiation. A perk is that templated functions that go unused aren't included in the compiled product at all.
|
|
|
Logged
|
"That is the single most cryptic piece of code I have ever seen." -Master PobbleWobble "I disapprove of what you say, but I will defend to the death your right to say it." -Evelyn Beatrice Hall, Friends of Voltaire
|
|
|
|
luiscubal
|
|
Reply #74 Posted on: January 29, 2010, 02:54:47 pm |
|
|
Joined: Jun 2009
Posts: 452
|
While it is true that templates can fill space in a horrible way, they can be very useful. As miky pointed out, they are automated copy and pasting. So if you actually need copy and pasting, then templates are probably the best solution. Templates are a way of doing metaprogramming in C++. Not sure how useful that is, though. Also, while it is true that templates copy-paste the code, that fact means the compiler can attempt more sophisticated tricks to improve runtime speed. So templates can improve speed at the expense of executable size.
|
|
|
Logged
|
|
|
|
|