Skip to main content
GameDev.net gamedev.net
🔒 Locked

Class templates

Started by BSXrider Jan 19, 2002 at 10:14 AM 1 replies 300+ views
Original Post
BSXrider
BSXrider
Very basic stuff. I''m going to write myself a vector class, as a learning exercise more than anything. If I write this class as a template (so I can have int vectors, float vectors, double vectors etc) are there any disadvantages? Does the compiler chuck in a version for each main data type even if they''re not used or anything silly like that, or are templates through-and-through a good idea? - seb
Null and Void
Null and Void
For a vector class templates would be a good choice. Think of it as "one copy of the code for each type that uses the template." So, if you do this:
  
template <class T> class Demo {
// ...

public:
void Alpha(void) { }
inline void Beta(void) { }
};

Demo <int> I;
Demo <float> F;

I.Alpha();
I.Beta();

F.Alpha();
F.Beta();

You''re going to have two functions for ''Alpha'' floating around (one for integers, the other for floats), but (hopefully) no functions for ''Beta'' floating around (since it was inlined). Remember that it isn''t worth inlining anything too big, but with templates inlining what you should pays off .

Gorg
Gorg
Also With templates you usually pay for what you use, so if you have class an you only use 3 ou of 10 functions, then only the code for those 3 functions will be defined.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.