Re: Singleton and static function
On Oct 31, 3:50 pm, Mosfet <mos...@anonymous.org> wrote:
Salt_Peter a =E9crit :
On Oct 31, 10:27 am, John Doe <mos...@anonymous.org> wrote:
Hi,
I have a singleton class defined like this :
class UIManager : public CSingleton<UIManager>,
pu=
blic CObject
{
protected:
DECLARE_DYNAMIC(UIManager)
friend class CSingleton<UIManager>;
UIManager();
virtual ~UIManager();
public:
...
};
and I was using this code like this :
A)
UIManager* l_pUiMgr = UIManager::GetInstance();
ASSERT (l_pUiMgr != NULL);
l_pUiMgr->GetResText( a_ResId, bStripHtml);
But I was fed up with always typing this so I have declared below my
UIManager class a static function :
static inline UIManager& UIManager() { return *(UIManager::GetInstance=
()); }
and I wanted to be able to call it like that :
UIManager().GetResText( a_ResId, bStripHtml);
The problem is I get some compilations errors with the code in A)
5>c:\wce_v42\inc\BaseView.h(227) : error C2065: 'l_pUiMgr' : undeclare=
d
identifier
Why I cannot write UIManager* now ?
Why don't you tell us? l_pUiMgr is an undeclared identifier. You are
doing something wrong, what that might be we don't know. Put together
a simple, compileable case forth without MS-specific macros.
I mean that the following line doesn't compile anymore :
UIManager* l_pUiMgr = UIManager::GetInstance();
but maybe I forgot one include ...- Hide quoted text -
- Show quoted text -
I had no problem, then again, i don't need MS code to do any of it.
i'ld suggest declaring a pointer only (which does not construct
anything) just to find out if UIManager is recognized as a complete
type.
UIManager* p_mgr;
If that fails then includes are indeed the issue and you should get an
error specifically stating what is not recognized as a known type. I
have no clue what header CSingleton is found in (only a Singleton can
access UIManager's protected constructor).
I will say that your setup should look like the following, which does
work, although my Singleton type needs a little more tightening to
prevent side-effects.
[OT]
MS and MFC as well as other languages like Java live in an 'everything
is an Object or CObject' world. As if an instance was somehow
otherwise NOT an object. That mentality is bad, nasty, buggy, insane,
dumb, stupid, etc.
[/OT]
#include <iostream>
class Object { };
template< typename T >
class Singleton
{
protected:
Singleton() { std::cout << "Singleton()\n"; }
~Singleton() { std::cout << "~Singleton()\n"; }
private:
Singleton(const Singleton& copy);
Singleton& operator= (const Singleton&);
public:
static T* const GetInstance()
{
static T t;
std::cout << "&t = " << &t << std::endl;
return &t;
}
};
class Manager : public Singleton< Manager >, public Object
{
friend class Singleton<Manager>;
protected:
Manager() { std::cout << "Manager()\n"; }
virtual ~Manager() { std::cout << "~Manager()\n"; }
};
int main()
{
Manager* p_mgr = Manager::GetInstance();
std::cout << "Manager* p_mgr = ";
std::cout << p_mgr << std::endl;
}