Boost logo

Boost :

From: Dave Abrahams (abrahams_at_[hidden])
Date: 2000-05-19 16:36:43


--- In boost_at_[hidden], Branko Èibej <branko.cibej_at_h...> wrote:

> for now, I'd appreciate any feedback to see if I'm on the right
track.

I took a look because I needed a singleton for work today. Frankly, I
had a hard time understanding it. There seemed to be a lot of runtime
checking. I whipped this thing up instead which matched my usage
model exactly. Fortunately, it is part of an open-source project.
Let's compare notes:

struct Empty {};
template <class Derived, class Base = Empty>
struct Singleton : Base
{
    typedef Singleton SingletonBase; // Convenience type for derived
class constructors
    
    static Derived* singleton();

    // Pass-through constructors
    Singleton() : Base() {}
    
    template <class A1>
    Singleton(const A1& a1) : Base(a1) {}
    
    template <class A1, class A2>
    Singleton(const A1& a1, const A2& a2) : Base(a1, a2) {}
    
    template <class A1, class A2, class A3>
    Singleton(const A1& a1, const A2& a2, const A3& a3) : Base(a1,
a2, a3) {}
};

template <class Derived, class Base>
Derived* Singleton<Derived,Base>::singleton()
{
    static Derived x;
    return &x;
}

//usage:

class Foo : public Singleton<Foo, OptionalBaseClass>
{
private:
   Foo();
   friend class SingletonBase;
   //...more stuff...
};

-Dave


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk