472,977 Members | 1,686 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,977 software developers and data experts.

Re-usable singleton class that can construct pointers to objects with non-trivial constructors

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
{
T * operator()() const { return new T; }
};

template<typename T>
struct ValueCreatorFunctor
{
ValueCreatorFunctor(const T& val) : val_(val) {}

T * operator()() const { return new T(val_); }

private:
T val_;
};

/* Users can add more functors for more elaborate types. */

template <typename T1, typename T2>
class Singleton
{
public:
static T1 * get_instance(const T2& creator)
{
if (!obj)
{
obj = creator();
}

return obj;
}

private:
Singleton() {}

static T1 *obj;
};

template <typename T1, typename T2>
T1 * Singleton<T1, T2>::obj = 0;

#endif /* #ifndef SINGLETON_HPP */

As you can see I've provided to default functor, one for default-
constructing and one for objects with a constructor that takes a
single value.

I've made the following test program:

#include <iostream>
#include <string>

#include "singleton.hpp"

using namespace std;

int
main()
{
int *n = Singleton<int, ValueCreatorFunctor<int>
>::get_instance(ValueCreatorFunctor<int>(4711));
cout << *n << endl;

delete n;

string *s = Singleton<string, DefaultCreatorFunctor<string>
>::get_instance(DefaultCreatorFunctor<string>()) ;
cout << *s << endl;

delete s;

return 0;
}
it seems to work but somehow I don't feel very satisfied. The syntax
for obtaining an instance is not elegant and if you want to a more
elaborate class to be handled as a singleton, you will have to write
your own functor (basically a ValueCreatorFunctor with additional
parameters). It was however a good exercise in templates and functors
for me and for that I'm glad.

Also I was thinking about ways in which I could make the singleton
delete its pointer when the program exits, so the user doesn't have to
worry about that (and risk double deletes).

As always, I would like comments from you. :-)

- Eric

Aug 14 '07 #1
2 1838
On 14 Srp, 19:44, Eric Lilja <mindcoo...@gmail.comwrote:
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
{
T * operator()() const { return new T; }

};

template<typename T>
struct ValueCreatorFunctor
{
ValueCreatorFunctor(const T& val) : val_(val) {}

T * operator()() const { return new T(val_); }

private:
T val_;

};

/* Users can add more functors for more elaborate types. */

template <typename T1, typename T2>
class Singleton
{
public:
static T1 * get_instance(const T2& creator)
{
if (!obj)
{
obj = creator();
}

return obj;
}

private:
Singleton() {}

static T1 *obj;

};

template <typename T1, typename T2>
T1 * Singleton<T1, T2>::obj = 0;

#endif /* #ifndef SINGLETON_HPP */

As you can see I've provided to default functor, one for default-
constructing and one for objects with a constructor that takes a
single value.

I've made the following test program:

#include <iostream>
#include <string>

#include "singleton.hpp"

using namespace std;

int
main()
{
int *n = Singleton<int, ValueCreatorFunctor<int>
::get_instance(ValueCreatorFunctor<int>(4711));

cout << *n << endl;

delete n;

string *s = Singleton<string, DefaultCreatorFunctor<string>
::get_instance(DefaultCreatorFunctor<string>());

cout << *s << endl;

delete s;

return 0;

}

it seems to work but somehow I don't feel very satisfied. The syntax
for obtaining an instance is not elegant and if you want to a more
elaborate class to be handled as a singleton, you will have to write
your own functor (basically a ValueCreatorFunctor with additional
parameters). It was however a good exercise in templates and functors
for me and for that I'm glad.

Also I was thinking about ways in which I could make the singleton
delete its pointer when the program exits, so the user doesn't have to
worry about that (and risk double deletes).

As always, I would like comments from you. :-)

- Eric
Hi.

I have few comments:
1. Method get_instance should be named create_instance, because it
always creates new instance.
2. To delete singleton object at the end of program, look at the
atexit function in <cstdlib>
3. If you need variable parameters, you can give yourself a limit,
let's say 10 parameters as maximum. Then you can write such function
this way:

template<typename T>
class SomeClass
{
public:
// .. Some stuff ...

T* Func() { return new T(); }

template<P1 p1>
T* Func(P1 p1) { return new T(p1); }

template<typename P1 p1, typename P2 p2>
T* Func(P1 p1, P2 p2) { return new T(p1, p2); }

template<typename P1 p1, typename P2 p2, typename P3 p3>
T* Func(P1 p1, P2 p2, P3 p3) { return new T(p1, p2, p3); }

// etc.
};

Only used member functions will be generated, so you do not have to
worry about size. If you will try function with wrong parameters,
you'll get compilation error.

Aug 14 '07 #2
On 14 Aug, 23:04, Ondra Holub <ondra.ho...@post.czwrote:
On 14 Srp, 19:44, Eric Lilja <mindcoo...@gmail.comwrote:
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
{
T * operator()() const { return new T; }
};
template<typename T>
struct ValueCreatorFunctor
{
ValueCreatorFunctor(const T& val) : val_(val) {}
T * operator()() const { return new T(val_); }
private:
T val_;
};
/* Users can add more functors for more elaborate types. */
template <typename T1, typename T2>
class Singleton
{
public:
static T1 * get_instance(const T2& creator)
{
if (!obj)
{
obj = creator();
}
return obj;
}
private:
Singleton() {}
static T1 *obj;
};
template <typename T1, typename T2>
T1 * Singleton<T1, T2>::obj = 0;
#endif /* #ifndef SINGLETON_HPP */
As you can see I've provided to default functor, one for default-
constructing and one for objects with a constructor that takes a
single value.
I've made the following test program:
#include <iostream>
#include <string>
#include "singleton.hpp"
using namespace std;
int
main()
{
int *n = Singleton<int, ValueCreatorFunctor<int>
>::get_instance(ValueCreatorFunctor<int>(4711));
cout << *n << endl;
delete n;
string *s = Singleton<string, DefaultCreatorFunctor<string>
>::get_instance(DefaultCreatorFunctor<string>()) ;
cout << *s << endl;
delete s;
return 0;
}
it seems to work but somehow I don't feel very satisfied. The syntax
for obtaining an instance is not elegant and if you want to a more
elaborate class to be handled as a singleton, you will have to write
your own functor (basically a ValueCreatorFunctor with additional
parameters). It was however a good exercise in templates and functors
for me and for that I'm glad.
Also I was thinking about ways in which I could make the singleton
delete its pointer when the program exits, so the user doesn't have to
worry about that (and risk double deletes).
As always, I would like comments from you. :-)
- Eric

Hi.

I have few comments:
1. Method get_instance should be named create_instance, because it
always creates new instance.
No it doesn't, it only creates one one obj == 0.
2. To delete singleton object at the end of program, look at the
atexit function in <cstdlib>
Sounds like a c-ism to me, what about a smart pointer? It's time I
started to use them.
3. If you need variable parameters, you can give yourself a limit,
let's say 10 parameters as maximum. Then you can write such function
this way:

template<typename T>
class SomeClass
{
public:
// .. Some stuff ...

T* Func() { return new T(); }

template<P1 p1>
T* Func(P1 p1) { return new T(p1); }

template<typename P1 p1, typename P2 p2>
T* Func(P1 p1, P2 p2) { return new T(p1, p2); }

template<typename P1 p1, typename P2 p2, typename P3 p3>
T* Func(P1 p1, P2 p2, P3 p3) { return new T(p1, p2, p3); }

// etc.

};

Only used member functions will be generated, so you do not have to
worry about size. If you will try function with wrong parameters,
you'll get compilation error.
Interesting approach.

Aug 14 '07 #3

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

Similar topics

1
by: Nel | last post by:
I have a question related to the "security" issues posed by Globals ON. It is good programming technique IMO to initialise variables, even if it's just $foo = 0; $bar = ""; Surely it would...
4
by: Craig Bailey | last post by:
Anyone recommend a good script editor for Mac OS X? Just finished a 4-day PHP class in front of a Windows machine, and liked the editor we used. Don't recall the name, but it gave line numbers as...
1
by: Chris | last post by:
Sorry to post so much code all at once but I'm banging my head against the wall trying to get this to work! Does anyone have any idea where I'm going wrong? Thanks in advance and sorry again...
11
by: James | last post by:
My form and results are on one page. If I use : if ($Company) { $query = "Select Company, Contact From tblworking Where ID = $Company Order By Company ASC"; }
4
by: Alan Walkington | last post by:
Folks: How can I get an /exec'ed/ process to run in the background on an XP box? I have a monitor-like process which I am starting as 'exec("something.exe");' and, of course the exec function...
1
by: John Ryan | last post by:
What PHP code would I use to check if submitted sites to my directory actually exist?? I want to use something that can return the server code to me, ie HTTP 300 OK, or whatever. Can I do this with...
10
by: James | last post by:
What is the best method for creating a Web Page that uses both PHP and HTML ? <HTML> BLA BLA BLA BLA BLA
8
by: Beowulf | last post by:
Hi Guru's, I have a query regarding using PHP to maintain a user profiles list. I want to be able to have a form where users can fill in their profile info (Name, hobbies etc) and attach an...
1
by: joost | last post by:
Hello, I'm kind of new to mySQL but more used to Sybase/PHP What is illegal about this query or can i not use combined query's in mySQL? DELETE FROM manufacturers WHERE manufacturers_id ...
2
by: sky2070 | last post by:
i have two file with jobapp.html calling jobapp_action.php <HTML> <!-- jobapp.html --> <BODY> <H1>Phop's Bicycles Job Application</H1> <P>Are you looking for an exciting career in the world of...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
4
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

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.