473,881 Members | 1,704 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Singleton template

Is there such a thing as a Singleton template that actually saves
programming effort?
Is it possible to actually use a template to make an arbitrary class a
singleton without having to:

a) explicitly make the arbitrary class's constructor and destructor private
b) declare the Singleton a friend of the arbitrary class

If not, then a singleton template is no better than cutting and pasting a
one-liner like this:

C
{
C& Instance() { static C instance; return instance; }
:
};

Any thoughts from template gurus?
Tim Clacy
An instance of the Simpleton pattern?
Jul 19 '05 #1
7 12483
Tim Clacy wrote:
Is there such a thing as a Singleton template that actually saves
programming effort?
I have one, so I don't have to recode all the time.
When most everything is the same but the types differ, that
is when a template is useful.
Is it possible to actually use a template to make an arbitrary class a
singleton without having to:

a) explicitly make the arbitrary class's constructor and destructor private
b) declare the Singleton a friend of the arbitrary class

If not, then a singleton template is no better than cutting and pasting a
one-liner like this:

C
{
C& Instance() { static C instance; return instance; }
:
};

Any thoughts from template gurus?
Tim Clacy
An instance of the Simpleton pattern?


How about this:
#ifndef SINGLETON_HPP
#define SINGLETON_HPP

//-------------------------------------------------------------------------
// File: singleton.hpp
//
// Class: Singleton
//
// Copyright (C) 2001 - 2003, Thomas Matthews
//
// PROPRIETARY NOTICE
//
// This document is the property of Thomas Matthews, with the
// information herein reserved as proprietary to Thomas Matthews,
// and is not to be published, reproduced, copied, disclosed,
// or used without the express written consent of a duly
// authorized representative of Thomas Matthews
//
// Description:
// This class represents the Singleton Design Pattern.
//
// Notes:
// 1. A singleton allows only one instantiation of a class.
//
// Usage:
// #include "singleton. hpp"
// using namespace Common;
// class My_Class
// : public Singleton<My_Cl ass>
// {
// friend class Singleton<My_Cl ass>;
// protected:
// My_Class();
// };
//
// Recent History {most recent first}:
// 05 Nov 2001 TOM Correction: Changed variable in ref() to static.
//
// Extended history at end of file.
//-------------------------------------------------------------------------

namespace Common
{

template <class Target>
class Singleton
{
//---------------------------------------------------------------------
// Public types
//---------------------------------------------------------------------
public:

//---------------------------------------------------------------------
// Public Constructors & Destructors
//---------------------------------------------------------------------
public:
virtual ~Singleton(); // destructor.

//---------------------------------------------------------------------
// Public Overloaded Operators
//---------------------------------------------------------------------
public:

//---------------------------------------------------------------------
// Public methods
//---------------------------------------------------------------------
public:
static Target * ptr(void);
static Target & ref(void);

//---------------------------------------------------------------------
// Protected methods
//---------------------------------------------------------------------
protected:
Singleton(); // Default constructor

//---------------------------------------------------------------------
// Protected members
//---------------------------------------------------------------------
protected:

//---------------------------------------------------------------------
// Private methods
//---------------------------------------------------------------------
private:

//---------------------------------------------------------------------
// Private members
//---------------------------------------------------------------------
private:

};
//-------------------------------------------------------------------------
// Singleton Exceptions
//-------------------------------------------------------------------------
class Singleton_Excep tions
{
public:
Singleton_Excep tions()
{ ; };
};
//-------------------------------------------------------------------------
// Singleton Constructors & Destructors
//-------------------------------------------------------------------------
template <class Target>
inline
Singleton<Targe t> ::
Singleton()
{
}
template <class Target>
inline
Singleton<Targe t> ::
~Singleton()
{
}
//-------------------------------------------------------------------------
// Singleton Overloaded Operators
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Singleton methods in alphabetical order
//-------------------------------------------------------------------------
template <class Target>
Target *
Singleton<Targe t> ::
ptr(void)
{
return &(ref());
}
template <class Target>
Target &
Singleton<Targe t> ::
ref(void)
{
static Target the_instance;
return the_instance;
}
} // End namespace: Common
//-------------------------------------------------------------------------
// Extended history, most recent entry first.
//
// 30 Oct 2001 TOM Created.
//-------------------------------------------------------------------------
#endif // SINGLETON_HPP
--
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.l earn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book

Jul 19 '05 #2
Thomas Matthews wrote:
Is it possible to actually use a template to make an arbitrary class a
singleton without having to:

a) explicitly make the arbitrary class's constructor and destructor
private
No, AFAICT. See below.
b) declare the Singleton a friend of the arbitrary class

[snip] // Usage:
// #include "singleton. hpp"
// using namespace Common;
// class My_Class
// : public Singleton<My_Cl ass>
// {
// friend class Singleton<My_Cl ass>;
// protected:
// My_Class();
// };
This implementation does not meet requirement (b).

As for requirement (a)...
template <class Target>
Target &
Singleton<Targe t> ::
ref(void)
{
static Target the_instance;
return the_instance;
}


The static Target declaration demands that Target have a public constructor.

I distilled Thomas Matthews' code to the following:

template <typename T>
class Singleton {
protected:
Singleton() {}

public:
static T* getptr() { return &(getref()); }
static T& getref();

virtual ~Singleton() {}
};

template <typename T>
inline T& Singleton<T>::g etref()
{
static T ref;
return ref;
}

This allows

class B : public Singleton<B> {}

which lets you use B::getptr and B::getref to refer to a single instance
of B, but does not prevent instantiations of other B objects. Adding

friend class Singleton<B>;

to the declaration of B allows you to make B's default constructor
private, but violates both of OP's requirements. Anyhow, if B requires
some kind of member initialization, you will need to decalre a default
constructor, which either violates requirement (a) or the Singleton pattern.

/david

--
"As a scientist, Throckmorton knew that if he were ever to break wind in
the echo chamber, he would never hear the end of it."

Jul 19 '05 #3

"Tim Clacy" <no*******@nosp amphaseone.nosp amdk> wrote in message
news:3f******** *************@n ews.dk.uu.net.. .
Is there such a thing as a Singleton template that actually saves
programming effort?
Is it possible to actually use a template to make an arbitrary class a
singleton without having to:

a) explicitly make the arbitrary class's constructor and destructor private b) declare the Singleton a friend of the arbitrary class

If not, then a singleton template is no better than cutting and pasting a
one-liner like this:


[SNIP]

This statement is not generally true. If you consider more difficult and
sophisticated singelton variations (Phoenix Singleton and so on) you'll see
that templates come in very handy especially if you use policies to create a
fully user configurable singleton pattern. I'd recommend to check out a good
pattern design book (Gang of Four) and Modern Design C++.

HTH
Chris
Jul 19 '05 #4

"Thomas Matthews" <Th************ **********@sbcg lobal.net> wrote in message
news:Ot******** **********@news svr32.news.prod igy.com...
[SNIP]

There is one problem with your singleton approach because it's not failsave
against compile synthesized copy ctors. For example:

My_Class& ObjRef = My_Class::ref() ;
ObjRef.m_X = 5;
cout << ObjRef.m_X << endl;
My_Class& ObjRef2 = My_Class::ref() ;
ObjRef2.m_X = 7;
cout << ObjRef.m_X << endl;

My_Class Obj3( My_Class::ref() ); // sneaky copy is possible
Obj3.m_X = 99;
cout << Obj3.m_X << endl;
cout << ObjRef.m_X << endl;

One possible solution would be to implement the singleton as a wrapper and
enforce the check that the wrapped object is for example derived from a
class CNonCopyable.

class CNonCopyable {
protected:
CNonCopyable() {};
virtual ~CNonCopyable() {};
private:
CNonCopyable( const CNonCopyable& rhs );
CNonCopyable& operator=(const CNonCopyable& rhs );
};

Regards
Chris
Jul 19 '05 #5
Tim
"Thomas Matthews" <Th************ **********@sbcg lobal.net> wrote in message
news:Ot******** **********@news svr32.news.prod igy.com...
Tim Clacy wrote:
Is there such a thing as a Singleton template that actually saves
programming effort?


Thomas, your template is pretty much like my best effort; note that it's
more work to make an arbitary class a singleton by using a template than it
is to cut and paste a one-liner... which I find troubling, not because I'm,
lazy but because it suggests that there's something wrong with the language.
Tim
Jul 19 '05 #6
Tim

"Chris Theis" <Ch************ *@nospam.cern.c h> wrote in message
news:bn******** **@sunnews.cern .ch...

"Tim Clacy" <no*******@nosp amphaseone.nosp amdk> wrote in message
news:3f******** *************@n ews.dk.uu.net.. .
Is there such a thing as a Singleton template that actually saves
programming effort?
Is it possible to actually use a template to make an arbitrary class a
singleton without having to:

a) explicitly make the arbitrary class's constructor and destructor private
b) declare the Singleton a friend of the arbitrary class

If not, then a singleton template is no better than cutting and pasting a one-liner like this:


[SNIP]

This statement is not generally true. If you consider more difficult and
sophisticated singelton variations (Phoenix Singleton and so on) you'll

see that templates come in very handy especially if you use policies to create a fully user configurable singleton pattern. I'd recommend to check out a good pattern design book (Gang of Four) and Modern Design C++.

HTH
Chris


I think I might have come across the complex Singleton example you refer to;
is it the one where you can control how the object is allocated (e.g. using
new or some other means) and how it's life-time is managed?

I'm reasonably familiar with the original GoF Design Patterns and loosely
familiar with a few dozen other trendy patterns; in fact, it seems every one
and his dog has a pattern now.
Jul 19 '05 #7

"Tim" <ti******@hotma il.com> wrote in message
news:bn******** **@news.cyberci ty.dk...


I think I might have come across the complex Singleton example you refer to; is it the one where you can control how the object is allocated (e.g. using new or some other means) and how it's life-time is managed?
Yes exactly.

I'm reasonably familiar with the original GoF Design Patterns and loosely
familiar with a few dozen other trendy patterns; in fact, it seems every one and his dog has a pattern now.


You're probably right, but they are sometimes quite useful.

Chris
Jul 19 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
5879
by: Sean Dettrick | last post by:
Hi, apologies for yet another Singleton posting. From reading around previous postings etc, I've cobbled together two Singleton template definitions - one that returns a reference, and one that returns a pointer. I understand the pointer one and it works, but the reference one doesn't work as I expect. Can anybody explain this to me? (Code below). I'm not really looking for thread safety or for something as general
1
2456
by: Jim Strathmeyer | last post by:
So I'm trying to implement a singleton template class, but I'm getting a confusing 'undefined reference' when it tries to link. Here's the code and g++'s output. Any help? // singleton.h template <class T> class Singleton : public T { public: static T * Instance();
3
2504
by: Alicia Roberts | last post by:
Hello everyone, I have been researching the Singleton Pattern. Since the singleton pattern uses a private constructor which in turn reduces extendability, if you make the Singleton Polymorphic what sort of problems/issues should be considered? Also, I see that a singleton needs to be set up with certain data such as file name, database URL etc. What issues are involved in this, and how would you do this? If someone knows about the...
5
5315
by: Pelle Beckman | last post by:
Hi, I've done some progress in writing a rather simple singleton template. However, I need a smart way to pass constructor arguments via the template. I've been suggested reading "Modern C++ Design" or similar books, but I feel there are full of clever guys here who could help me out.
2
3917
by: yccheok | last post by:
hello, in a singleton design, i trying to make my parent class having protected constructor and destructor. however, the compiler give me error when my child, trying to delete itself through parent pointer. isn't child should have access to parent protected destructor? thank you. class CMachineFactory
3
5746
by: Raider | last post by:
I need to have one object for each template argument(s) used. For example, I need to have one object of int. I tried the following code and it gives me all I want with Visual C++ 7.1. But is it portable??? Will all compilers produce code that prints "single"? Instancing of object right in header file (that can be include multiple times - i.e. in multiple cpp files) give rise to my doubts... Singleton.cpp
15
3062
by: Nick Keighley | last post by:
Hi, I found this in code I was maintaining template <class SingletonClass> SingletonClass* Singleton<SingletonClass>::instance () { static SingletonClass _instance; return &_instance; }
2
530
by: ben chang | last post by:
i'm hacking at some code originally written for VC++, trying to port to linux GCC 4. the linker returns multiple-definition errors with a singleton object, which i guess is not a problem in visual c++. i'll try to excerpt the relevant parts without posting all the source files (it's the maya exporter for the Ogre 3D engine). there's a pretty standard-looking Singleton template, and in a file called "materialSet.h" we have a class using...
2
1895
by: Eric Lilja | last post by:
As the topic says, I wanted to make a re-usable singleton class that could create pointers to objects with non-trivial constructors. I came up with this: #ifndef SINGLETON_HPP #define SINGLETON_HPP template<typename T> struct DefaultCreatorFunctor {
0
11095
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10716
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9552
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7952
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5780
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5976
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4597
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4194
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3223
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.