Well, Valmont, let it never be said you didn't warn me.
I tried using templates to create a dynamically resizable array of any datatype. I'm stumped... like a tree.
Here's what I have so far.
Code:
#ifndef dvar_h
#define dvar_h
//////////////////////////////////////////////////
/* dVar.h ------------------ Work on templates. */
//////////////////////////////////////////////////
template <class dataType>
class dVar
{
private:
dataType internalData[1];
public:
dVar( unsigned int arraySize );
~dVar();
dataType getData( unsigned int valueNumber );
void setData( unsigned int valueNumber, dataType newValue );
};
//////////////////////////////////////////////////
/* ----------- Functions for dVar.h ----------- */
//////////////////////////////////////////////////
// Name: Initializer (Constructor)
// Function: Resize array and fill it with the value defaultValue.
template <class dataType>
dVar<dataType>::dVar( unsigned int arraySize )
{
// And the nightmare begins when I unquote the following line.
// internalData = new dataType[ arraySize ];
}
// Name: Deconstructor
// Function: Guess.
template <class dataType>
dVar<dataType>::~dVar()
{
delete[] internalData;
}
// variable.getData( NUMBER );
// Name: getData
// Function: Returns the value of the item in position NUMBER.
template <class dataType>
dataType dVar<dataType>::getData( unsigned int valueNumber )
{
return internalData[ valueNumber ];
}
// variable.setData( NUMBER, VALUE );
// Name: setData
// Function: Set the value of the item in position NUMBER equal to VALUE.
template <class dataType>
void dVar<dataType>::setData( unsigned int valueNumber, dataType newValue )
{
internalData[valueNumber] = newValue;
}
#endif Alrighty, here's what's bugging me.
Although I can create and return any data type, I can't resize the array.
I don't know what I'm going to do for irregular and custom types. (structs and classes).
I googled to find more information, but I'm kinda' at a loss as to whether this is a battle I can win.
Should I abort, retry, or BEER?
EDIT: Dah, evils and badstuffs. Should I have posted this under the other thread? It seems a bit off topic for that one.
EDIT... again: Fixed it! See below.
Code:
dataType internalData[1];
Should have been
Code:
dataType * internalData;
But still, my other question remains, how exactly would I make this compatable with abnormal data types?
E.g.
Code:
struct worker
{
char name[16];
unsigned int age;
};