Re: question on static member for class template
Chimanrao wrote:
here is a code snippet:
#include <iostream>
#include <string>
struct type_record
{
type_record(const std::string& str)
{
std::cout << str << "\n";
}
};
template <typename T>
class helper
{
private: // nothing uses the following member
static type_record reg;
};
template <typename T>
volatile type_record
helper<T>::reg(typeid(T).name());
template class helper<int>;
template class helper<float>;
template class helper<double>;
class mytest : public helper<char>
{
};
int main() {return 0;}
The output of this program is
int
float
double
no constructor is called for the static object for mytest
class. why is this?
Because you never define the static object.
In the case of a template class, two things are necessary for
the static object to be defined: you must provide a template
definition for it, and you must do something which causes the
definition to be instantiated. Neither of these is present in
the code you show.
Providing the template definition is easy: after the definition
of class helper, add a line:
template< typename T >
type_record helper< T >::reg ;
In order to trigger an instatiation, it is necessary to use the
object in some way. Perhaps by adding a constructor to helper:
helper() { ® }
(Even this won't suffice in the exact code above, but in almost
all real cases, it should be enough.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
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! ]