Re: Query: want a function that is called at initialisation time
tropostropos@hotmail.com wrote:
I have a class and I want a static member function of the class to run
at process initialisation time. What's the best way to do this? There
is a possible complication in that the class is templated. Here is my
current solution:
template<typename T> class Singleton
{ public:
static void initialise( ) { . . . }
static int dummy;
};
template<typename T> int Singleton<T>::dummy(
Singleton<T>::initialise( ), 999);
main( )
int main()
{
Singleton<MyClass> m;
}
At process initialisation, the static member Singleton<MyClass>::dummy
has to be initialised, and that causes the initialise( ) function to
be run before 999 is assigned to dummy. The problem is that this is
ugly. dummy serves no real purpose.
Not only it serves no real purpose except to invoke the 'initialise'
member, but I am not sure it's going to actually be instantiated
(it's static member of a template), unless you actually use it.
Is there a better way?
Better in what sense? Your "way" isn't good at all -- it doesn't
work. If it did, we should see "aha" in the output of this:
#include <iostream>
template<typename T> class Singleton
{
public:
static void initialise( ) { std::cout << "aha"; }
static int dummy;
};
template<typename T>
int Singleton<T>::dummy(Singleton<T>::initialise( ), 999);
int main( )
{
Singleton<double> m;
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]