Implementing singleton into multiply classes

J

John Eskie

Lets say I want to make multiply classes as singletons. A singleton skeleton
would be with a static member variable of the instance and a GetInstance
function.
Currently I have this functionality in all the classes where I need it but
I'd like to use templates or some other language construct so I can remove
the duplicated code.
A small example of what I'd like to do:

Singleton class functionality:
T *instance;
T *GetInstance();
....


class A
{
....implements the above
int varA;
};

Class B
{
.... also implements singleton
double varB;
};

Thanks in advance.
-- John
 
T

Thomas Matthews

John said:
Lets say I want to make multiply classes as singletons. A singleton skeleton
would be with a static member variable of the instance and a GetInstance
function.
Currently I have this functionality in all the classes where I need it but
I'd like to use templates or some other language construct so I can remove
the duplicated code.
A small example of what I'd like to do:

Singleton class functionality:
T *instance;
T *GetInstance();
...


class A
{
...implements the above
int varA;
};

Class B
{
... also implements singleton
double varB;
};

Thanks in advance.
-- John

Looks like the difference between class A and Class B [sic]
is the type of the member variable. If all stays the same
except the type, consider using templates.

template <class VarType>
class C
{
VarType varC;
};

As far as the Singleton goes, you could either make it
as a template or have the classes inherit from it.

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top