C++

Creating Generic Classes in C++ Using Templates

We can create generic classes using templates in C++. Generic classes can be used for different data types.

In the example below we have one template class that can queue based on the data type. Here the example demonstrates that same generic class can be used to queue char data type as well integer data type.

[code lang=”cpp”]#include
using namespace std;

template
class list {
data_t data;
list *next;
public:

list (data_t d);
void add(list *node) { node->next = this; next = 0; }
list *getnext() { return next; }
data_t getdata() { return data; }
};
template
list <data_t> :: list(data_t d) {
data = d;
next = 0;
}

void TestChars() {
list start (‘a’);
list *p, *last;
int i;

last = &start;
for (i = 0; i < 26; i++) { p = new list<char> (‘a’ + i); p->add(last);
last = p;
}
// Display the list
p = &start;
while (p)
{
cout < < p->getdata();
p = p->getnext();
}
}

void TestIntegers() {

// Lest use integers
list<int> start (1);
list<int> *p, *last;
int i;
last = &start;
for (i = 0; i < 10; i++) { p = new list<int> (1 + i); p->add(last);
last = p;
}
// Display the list
p = &start;
while (p)
{
cout < < p->getdata();
p = p->getnext();
}
}
int main() {

TestChars();
cout < < "\nOutput for Integers" << endl; TestIntegers(); return 0; }

[\code]

Output

[code lang="txt"]

C:\P4\Sw\C++\Template\GenericQueueClass>GenericQueue.exe
aabcdefghijklmnopqrstuvwxyz

[/code]

Output for Integers

[code]112345678910
C:\P4\Sw\C++\Template\GenericQueueClass>[/code]


0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *