Visit Jeremy's Blog.
Go Back > Forums > Non-*NIX Forums > Programming
User Name
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.


  Search this Thread
Old 06-20-2007, 01:00 PM   #1
Registered: Oct 2006
Distribution: Ubuntu
Posts: 69

Rep: Reputation: 16
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:

template <class Data>
struct node
    Data data;
    node *link;
That's just a node to a linked list. Now, here's my main function:

int main()
    node<int> *hp = new node<int>;
    return 0;
Now for the question... I know this syntax is wrong and won't work:

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:

class llist
    void addNode(int mi_dType);
    node *hp;

void llist::addNode(int mi_dType)
    if (mi_dType == 1)
        hp = new node<int>;
        hp = new node<string>;
Old 06-20-2007, 01:10 PM   #2
LQ Newbie
Registered: Jun 2006
Distribution: Fedora 7
Posts: 11

Rep: Reputation: 0
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.

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

Last edited by orhun; 06-20-2007 at 01:15 PM.


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
c++ class template doesn't work!! tagigogo Programming 2 11-02-2005 04:45 PM
Template class with a template member... Nicholas Bishop Programming 3 02-21-2005 08:27 PM
template class ckcheung0927 Programming 3 11-28-2004 03:59 PM
C++ - class template - linker errors? Wynd Programming 2 10-19-2004 03:54 PM
C++ template class syntax rong Programming 12 08-13-2003 12:26 PM > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 06:54 AM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration