// note: or, you can use boost::ref or boost::cref // http://www.boost.org/boost/ref.hpp template< class type> struct ref_t { ref_t( type & val) : m_val( val) {} operator type & () const { return m_val; } type & m_val; }; template< class type> ref_t< type> ref( type & val) { return val; } template< class type> ref_t< const type> cref( const type & val) { return val; } 1. Passing a reference // in file User.cpp struct User { User( long & nUsersCount) : m_nUsersCount( nUsersCount) { ++m_nUsersCount; } ~User() { --m_nUsersCount; } private: long & m_nUsersCount; }; // in file main.cpp long g_nLoggedOnUsersCount = 0; // the Admin is us - the program itself dependent_static< User> g_Admin( ref( g_nLoggedOnUsersCount)); // note: this is WRONG // in Users' constructor, this would not increment g_nLoggedOnUsersCount, // but a copy of it //dependent_static< User> g_Admin( g_nLoggedOnUsersCount); 2. Passing an object that has no copy-constructor #include <iostream> #include <fstream> struct App { App() {} std::ostream & log() { return std::cout; } private: App( const App &); }; struct View { View( App & app) { app.log() << "new view created" << std::endl; } }; // global static App g_app; // ERROR: cannot access private constructor // dependent_static< View> main_view( g_app); dependent_static< View> main_view( ref( g_app) ); 3a. Passing const_val const_val< const char*> LOG_NAME( get_prop( "log"), with_default_val( "applog.txt")); // note: we're passing a const_val_ref !!! dependent_static< std::ofstream> s_log( const_val_ref( LOG_NAME)); // ERROR: cannot access private constructor // dependent_static< std::ofstream> s_log( LOG_NAME); // ERROR: cannot convert from 'struct ref_t<class const_val<char const *> const >' // to 'const char *' // (this would need two conversions) // dependent_static< std::ofstream> s_log( cref( LOG_NAME)); std::ostream & get_log() { return s_log; } void use_log() { get_log() << "this is written to applog.txt" << std::endl; } 3b. Passing a dependent_static struct use_AllUsers { use_AllUsers( AllUsers & users) {} }; dependent_static< AllUsers> s_AllUsers; set_dependent_static_name usersname( s_AllUsers, "allusers"); // ERROR: cannot access private constructor // dependent_static< use_AllUsers> s_use_AllUsers( s_AllUsers); dependent_static< use_AllUsers> s_use_AllUsers( dependent_static_ref( s_AllUsers)); add_dependency_on_static depallusers( s_use_AllUsers, "allusers"); |