Re: question on static member for class template
James Kanze wrote:
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;
};
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.)
Adding pointless statements to a program is hardly the best way to
instantiate a template class or one of its members. Aside from missing
a semicolon, the expression "®" has no side effects. So the compiler
may issue a warning or even optimize it away completely - and therefore
not end up instantiating the object as intended. An even bigger problem
- and the reason that I would not recommend this technique - is that
the meaning of this statement has completely diverged from its purpose.
In other words, it's not at all clear what this expression is doing -
and why it should be remain - in the program. So even if the statement
survives the compiler, there's a good chance that another programmer
may remove it in the furure - and would do so for the same reason - the
statement doesn't appear to do anything.
To instantiate a template class object explicitly, it is best to use
the syntax that the C++ language has defined for this very purpose.
Explicit instantiation of a complete class - or of an individual member
- does not require that the instantiated object (or member) also be
"used" somewhere in the program.
Here is the explicit instantiation of helper<char>::ref:
template type_record helper<char>::reg;
Grreg
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]