#include "Singleton.hpp" #include #include using namespace std; class Logger : public Singleton< Logger > { public: DECLARE_SINGLETON( Logger ) void log( string s ) { cout << s << endl; } protected: Logger( ) { cout << "Logger created" << endl; } public: ~Logger( ) { cout << "Logger destroyed" << endl; } }; /* this works, and two loggers can coexist, but they have different type class DerivedLogger : public Logger { public: void log( string s ) { cout << "derived " << s << endl; } }; */ class X : public Singleton< X > { public: void doSomething( ) { logger.log( "X is doing something" ); } friend class Singleton< X >; protected: X ( ) : logger( Singleton< Logger >::instance( ) ) { logger.log( "Creating singleton X" ); } public: ~X( ) { logger.log( "Destroying singleton X" ); } private: Logger &logger; }; void f( ) { Logger &logger = Singleton< Logger >::instance( ); logger.log( "bla" ); } int main( void ) { f( ); X &x = Singleton< X >::instance( ); x.doSomething( ); // this would copy the object, noncopyable ensure we have // only a private copy cnostructor //Logger l1 = Singleton< Logger >::instance( ); // Logger anotherOne; this doesn't work, as expected // DerivedLogger anotherOne; the same here // see explanation above //DerivedLogger &l2 = Singleton< DerivedLogger >::instance( ); //l2.log( "blu" ); // we can't accidently destroy the logger //delete &logger; return 0; }