LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   dynamic template class (https://www.linuxquestions.org/questions/programming-9/dynamic-template-class-563251/)

erat123 06-20-2007 01:00 PM

dynamic template class
 
Hi All, first of all, thanks for all you do, you guys do great work!

I'm trying to make a template class and make it dynamic... I'll explain it better w/ the code:

Code:

template <class Data>
struct node
{
    Data data;
    node *link;
};

That's just a node to a linked list. Now, here's my main function:

Code:

int main()
{
    node<int> *hp = new node<int>;
    return 0;
}

Now for the question... I know this syntax is wrong and won't work:

Code:

node *hp = new node<int>;
but, is there a way to make that work? Basically what I'm asking is how to create a pointer to a template class, but then dynamically change what type of template class it is.

Here's a class example where I would want this to work:

Code:

class llist
{
public:
    void addNode(int mi_dType);
private:
    node *hp;
};

void llist::addNode(int mi_dType)
{
    if (mi_dType == 1)
        hp = new node<int>;
    else
        hp = new node<string>;
}


orhun 06-20-2007 01:10 PM

I can think of two ways.
  1. Take a look at boost::any.
  2. Derive your template node class from a base node class, and store that (base node class) in llist.

Edit:
boost::any: Actually, their example looks quite similar to yours.


All times are GMT -5. The time now is 11:41 AM.