Template Based Arrays of Objects





1.00/5 (14 votes)
Template based arrays of objects.
Introduction
Here's a template based class for dynamic arrays of any type of objects. Credit goes to Michael B. Comet (comet@comet-cartoons.com), who has the Copyright with all rights reserved. I just renamed most of the members and functions and added a Find
function.
Usage
These are three steps to use a template based array; to help understand how it works, let's say your project defines a class named MyClass
in a file called myclass.h:
// myclass.h header for the MyClass class
class MyClass
{
public:
int foo;
int bar;
MyClass();
~MyClass();
void DoSomething();
}
- Add tarray.h to your project.
- Place an include statement for "tarray.h" in myclass.h, which now becomes:
- Optionally, add a
typedef
statement to increase the readability of your code (highly recommended):
// myclass.h header for the MyClass class
#include "tarray.h"
class MyClass
{
public:
int foo;
int bar;
MyClass();
~MyClass();
void DoSomething();
}
// myclass.h header for the MyClass class
#include "tarray.h"
class MyClass
{
public:
int foo;
int bar;
MyClass();
~MyClass();
void DoSomething();
}
typedef CTArray<MyClass> MyClassArray;
Now anywhere in your program where you are in need of an array of MyClass
objects, you can declare a variable:
MyClassArray myclassarray;
And access the array in many ways, keeping the []
operator functionality as well as the class functionality:
// add a MyClass object
myclassarray.Append(myclassobject);
// access the MyClass object at position 0 members and functions
myclassarray[0].foo = 0;
myclassarray[0].bar = 1;
myclassarray[0].DoSomething();
I've found no limit to the type of objects you can declare a template based array for; you can use it for a simple array of integers as well for your most complicated classes. In C++, things usually get complicated for array classes containing arrays of other classes, but the template based approach works like a charm. In the next code excerpt, I use a template based array of 'facets' owning an array of 'polys', which in turn owns an array of 'vertices' with x, y, z floats:
Facets[nFacet].Polys[nPoly].Vertices[i].x += 1.0f;
and it works! But more to it, is that the IDE's intellisense works, presenting me with all of each class' functions and members after I punch the ".". Beautiful!
Quote
It is an important and popular fact that things are not always what they seem. For instance, on the planet Earth, man had always assumed that he was more intelligent than dolphins because he had achieved so much--the wheel, New York, wars, and so on--while all the dolphins had ever done was muck about in the water having a good time. But conversely, the dolphins had always believed that they were far more intelligent than man--for precisely the same reasons.
HGG 1:23