How can I use a non-trivial constructor with as little code duplication as possible?
From: William Payne (mikas493_no_spam_at_student.liu.se)
Date: 10/11/04
- Next message: Victor Bazarov: "Re: How can I use a non-trivial constructor with as little code duplication as possible?"
- Previous message: Kin Cho: "Re: best C++ browser"
- Next in thread: Victor Bazarov: "Re: How can I use a non-trivial constructor with as little code duplication as possible?"
- Reply: Victor Bazarov: "Re: How can I use a non-trivial constructor with as little code duplication as possible?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Mon, 11 Oct 2004 23:22:04 +0200
Hello, consider the following two classes (parent and child):
#ifndef SINGLETON_HPP
#define SINGLETON_HPP
#include <cstddef> /* NULL */
template <typename T>
class Singleton
{
public:
static T* get_instance()
{
if(!t)
{
t = new T;
}
return t;
}
private:
Singleton()
{
; /* Never reached. */
}
static T* t;
};
class int_singleton : public Singleton<int>
{
};
/* As with member functions of class templates, the definition must *
* be in the class header. When compilers properly support the export *
* keyword, definitions of member functions and static data members *
* can be moved to an implementation (.cpp) file. */
template <typename T>
T* Singleton<T>::t = NULL;
#endif /* #ifndef SINGLETON_HPP */
The int_singleton class is just an example, I will be using other
(user-defined classes) types in the "real application" (if I can make it
work).
If you look at Singleton::get_instance(), you see that when !t is true
it creates a new object of type T using the constructor that takes no
arguments. However, I need to use constructors that take several
arguments. How should I accomplish this so I get as little code
duplication as possible? I have several rather complex classes in my
program that, and there must be only one instance of each class at all
times, and I would like to use the base class Singleton as much as
possible. Maybe get_instance() should call a virtual create_object()
function when !t is true, a function I redefine in my subclasses?
Comments please, how should I solve this?
/ WP
- Next message: Victor Bazarov: "Re: How can I use a non-trivial constructor with as little code duplication as possible?"
- Previous message: Kin Cho: "Re: best C++ browser"
- Next in thread: Victor Bazarov: "Re: How can I use a non-trivial constructor with as little code duplication as possible?"
- Reply: Victor Bazarov: "Re: How can I use a non-trivial constructor with as little code duplication as possible?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|
|