LinuxQuestions.org
Visit Jeremy's Blog.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
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.

Notices

Reply
 
Search this Thread
Old 06-20-2007, 01:00 PM   #1
erat123
Member
 
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:

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>;
}
 
Old 06-20-2007, 01:10 PM   #2
orhun
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.

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

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


Reply


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


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

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