This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Funny way of using templates
- To: gcc-help at gcc dot gnu dot org
- Subject: Funny way of using templates
- From: Kerola Antti <antti dot kerola at insta dot fi>
- Date: Mon, 13 Aug 2001 17:23:06 +0300
I was shown a piece software developed with gcc 2.95.2. The source code
contains
something, which looks rather suspicious to me. Now, I would like to have
a more knowledgeable opinion.
The developer has aimed at creating a singleton class template which
automatically creates a static instance of the class derived from the
singleton
template. The simplified source code is below.
#include <iostream>
template<class T> class SingletonT
{
public:
virtual void foo() {}
SingletonT() {
singleton.foo();
}
private:
static T singleton;
};
template<class T> T SingletonT<T>::singleton;
class MySingleton: public SingletonT<MySingleton>
{
public:
MySingleton(){
cout << "Instantiating MySingleton" << endl;
}
};
main(){
}
The code works with gcc 2.95.2 on Solaris 2.5 (Sparc)
Still, two things seem kind of funny to me:
1) The derived class inherits a template of which template parameter is
the derived class itself. This creates a circular dependency
between the template base class and the derived class.
2) In order to have the template class instantiated, and the static member
initialized, there is a dummy function 'foo', which is called from the
template's constructor. This seems to cause the instantatiation of the
template class. If the call to 'foo' is removed, the template class will
not be instantiated.
Now I would like to know:
1)Is this something which is supposed to work according to the standard?
2)Is this likely to work also with future versions of gcc?
Antti
Antti