"Chr?stian Rousselle" <Ch*******@Rousselle.de> wrote in message
news:7b**************************@posting.google.c om...
Hello,
I want to do derive a class from a Singleton template base class. Is
there a way to solve the following problem:
Yes - don't even try this approach - it doesn't save you much
typing and what there is is simple and it
does the wrong thing.
template<class T>
class CSingleton
{
public:
static T& GetInstance(void)
{
static T obj;
return obj;
}
protected:
virtual ~CSingleton() { };
CSingleton() {};
};
class App : public CSingleton<App>
{
protected:
App();
friend class CSingleton<App>; // otherwise c'tor cannot be
called
// is there a better way?
};
class App1 : public App
{
protected:
App1();
friend class CSingleton<App1>;
Why?
App1 is not a CSingleton<App1> it is a CSingleton<App>
I doubt very much that this is what you intended.
};
int main()
{
App1::GetInstance(); // App::GetInstance() is called
And returns an App NOT an App1
}
Is there a way to solve this? I do not like the friend deklaration and
I want to be able to create objects of type App1.
Thank you.
Christian Rousselle
There is no foolproof way of deriving from singletons without dynamic
linking
( I java you would have the GetInstance method dynamically load a class
instance
given only the name as a string in the environment)
A method that can work is to have no templates and static methods in App as
follows:
class App
{
public:
App()
{
if( inst )
throw "Attempting to create second App";
inst = this;
}
virtual ~App()
{
// DO NOT delete inst (this is it)
}
static App* instance()
{
return inst;
}
// presumably virtual methods go here
private:
static App* inst;
};
// in App.cpp
App* app::inst = 0;
// in App1.h
class App1 : public App
{
public:
App1() {} // calls App ctor and hence App::inst points to this.
};
// In the file containing main
static App1 app; // or AppN app - the most derived one
I find this technique simple and way more useful when testing because you
can replace App
with a test version which is impossible with the function static approach.
P.S. Don't get too hung up on trying to make the compiler prohibit
everything -
The public ctor will not be a problem in practice.