"Damien" <da************@gmail.comwrote in message
news:11**********************@l12g2000cwl.googlegr oups.com...
: I'm using a pretty standard C++ Singleton class, as below:
:
: template <typename T>
: class Singleton
: {
: public:
: static T* Instance()
: {
: static T instance_;
: return &instance_;
: }
:
: private:
: Singleton(); // ctor hidden
: ~Singleton(); // dtor hidden
: Singleton(Singleton const&); // copy ctor hidden
: Singleton& operator=(Singleton const&); // assign op hidden
: };
:
: Trying to use it on something really simple is giving me headaches:
:
: class DoIt
: {
: public:
: DoIt(){}
: ~DoIt(){}
:
: void DoSomething(){}
: };
:
: int main()
: {
: DoIt* doit = Singleton<DoIt>::Instance();
: doit->DoSomething();
: }
:
: I get the compiler error "error: expected constructor, destructor, or
: type conversion before '->' token" on the doit->DoSomething(); line.
I
: can't see how doit can be name-dependent because there's no
typedef'ing
: associated with it inside the Singleton, unless the static has
: something to do with it. Anyone got any ideas?
Well, the code you posted compiles "as is" in both Comeau and VC8.1.
However, the design of your singleton seems weird to me (was it an
artificial example posted for demonstration purposes?), and it does
not prevent the creation of additional DoIt instances.
Your "Singleton" class could be replaced with a single function:
template<class T>
T& single_instance() { static T instance; return instance; }
Usage:
int main()
{
DoIt& doit = single_instance<DoIt>();
doit.DoSomething();
}
An online search will probably bring a few existing singleton
implementations, up to Andrei Alexandrescu's policy-based design.
But if the 'static function member' does what you need, I personally
wouldn't bother using a Singleton template to implement it.
hth -Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <
http://www.brainbench.com