|
Boost : |
From: Alf P. Steinbach (alf_p_steinbach_at_[hidden])
Date: 2005-03-25 22:00:49
Jason Hise wrote:
> Early on, I had the idea to disable creation of a user's singleton by
> making the base class have one pure virtual function. The user's
> derived singleton would become an abstract class, and thus not be able
> to be instantiated. Then the user would refer to the singleton via an
> even further derived class, like follows:
>
> class singleton_base
> {
> private:
> virtual void define_to_enable_creation ( ) = 0;
> };
>
> template < typename Type >
> class singleton : public Type
> {
> private:
> virtual void define_to_enable_creation ( ) { }
>
> protected:
> // constructors and such were here
>
> public:
> // interface was here
> };
>
> //-------------------------------------------------
>
> class test_singleton : public singleton_base
> {
> public:
> void do_something ( );
> };
>
>
> int main ( )
> {
> test_singleton t; // this line would not compile
> singleton < test_singleton > t2; // neither would this
> singleton < test_singleton >::pointer ptr; // this would be the
> only access mechanism
> ptr->do_something ( );
>
> return 0;
> }
I'm not really sure what the _goal_ of this is, but let's say
* You want the client code to be able to derive from your
singleton_base.
* There should only be one instance ever of singleton_base
or a derived class.
* You want to protect against accidental instantiations.
Then what's wrong with the client code implementing a factory
function, e.g. in terms of a generic one?
class singleton_base
{
protected:
singleton_base() {}
template< class Derived >
static singleton_base& instance_()
{
static Derived theInstance;
return theInstance;
}
public:
// whatever.
static singleton_base& instance(); // Impl. by client.
};
Hth.,
- Alf
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk