|
Boost : |
From: Peter Dimov (pdimov_at_[hidden])
Date: 2005-02-14 16:27:14
Jorge Lodos wrote:
>
> Thank you for your comments. I agree with everything you said and try
> to avoid singletons in the first place. However, I have a practical
> problem
> that I have been able to "solve" only thru singletons.
> In a header only library that uses a class factory, the registration
> of objects with the factory is performed in a constructor of an
> object inside
> an anonymous namespace. Since the header may be #included more that
> once, I made those objects singletons to avoid multiple registration.
> The singleton::instance method may be called more that once without
> need, that's why I put "solve" in quotes. Since the object is inside
> an anonymous namespace, I can not use templates, which never get
> instantiated.
> If you or anyone else have a suggestion that allows for automatic
> registration without using singletons please share it :-)
Can you use something like the following:
class auto_reg
{
static int count_;
auto_reg()
{
if( ++count_ == 1 ) register();
}
~auto_reg()
{
if( --count_ == 0 ) unregister();
}
};
int auto_reg::count_;
To make it header-only use the template<class _ = void> trick.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk