DynamicTypeList list;
list.add(42);
list.add("forty-two");
for (DynamicType* item = list.begin(); item != list.end(); item++) {
if (item->what_type == item->is_int) {
cout << item->integer << endl;
} else if (item->what_type == item->is_string) {
cout << item->string << endl;
}
}
Dynamically Typed Dynamic List Example
class DynamicType {
public:
union {
int integer;
char* string;
};
enum {
is_int,
is_string
} what_type;
};
class DynamicTypeList {
DynamicType* data;
DynamicType* data_begin;
DynamicType* data_end;
int len;
int actual_len;
void expand() {
int oldlen = actual_len;
actual_len *= 2;
DynamicType* temp = new DynamicType[actual_len];
DynamicType* temp_begin = temp;
data = data_begin;
for (int i = 0; i < oldlen; i++) {
temp->what_type = data->what_type;
if (temp->what_type == temp->is_int)
temp->integer = data->integer;
else if (temp->what_type == temp->is_string)
temp->string = data->string;
temp++;
data++;
}
delete[] data_begin;
data = temp;
data_end = temp;
data_begin = temp_begin;
}
public:
DynamicTypeList() {
constructor(100);
}
DynamicTypeList(int actual_len) {
constructor(actual_len);
}
void constructor(int actual_len) {
len = 0;
this->actual_len = actual_len;
data = new DynamicType[actual_len];
}
~DynamicTypeList() {
delete[] data_begin;
}
void add(int i) {
if (len == actual_len) expand();
len++;
data->what_type = data->is_int;
data->integer = i;
data_end = data;
if (len == 1) data_begin = data;
data++;
}
void add(char* sz) {
if (len == actual_len) expand();
len++;
data->what_type = data->is_string;
data->string = sz;
data_end = data;
if (len == 1) data_begin = data;
data++;
}
DynamicType* begin() const {
return data_begin;
}
DynamicType* end() const {
return data_end + 1;
}
};
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.