Re: Curiously Recurring Template Pattern
Lukas Hosek wrote:
I've been searching the Internet for some nice implementations of the
singleton design pattern and I've come across this piece of code:
template<typename T> class Singleton
{
public:
static T& Instance()
{
static T theSingleInstance;
return theSingleInstance;
}
};
class OnlyOne : public Singleton<OnlyOne>
{
//..rest of interface defined here
};
My question is: it seems to me that the definition of the
OnlyOne class is some sort of indefinitely recursive, but,
surprisingly, it still compiles and works without any
problems. How is it possible? Doesn't the compiler need to
know how does Singleton<OnlyOne> look, before it can derive
OnlyOne from it? And doesn't the compiler need to know how
does OnlyOne look, before it can instantiate the Singleton
template with it?
Sort of. When the compiler sees the line
class OnlyOne : public Singleton< OnlyOne >
it will instantiate the class definition of Singleton for the
type OnlyOne -- if this class definition requires a definition
(and not just a declaration) of OnlyOne, it is an error. The
class definition, however, does NOT include the definition of
any member functions; these are only instantiated where (and
if) they are called. In this example, the template class
Singleton does not need the definition of T; a forward
declaration suffices. The function Singleton::Instance does
need the full definition, but that function will only be
instantiated when it is called, and it can only be called in
contexts where the full definition of OnlyOne is available.
--
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]