Re: question on static member for class template
Greg Herlihy ha scritto:
James Kanze wrote:
Chimanrao wrote:
#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.)
In this case this trick it's not necessary, because the OP is using
explicit instantiation of the class template. Explicit instantiation
will always instantiate all class members, including static data members
(?14.7.2/7).
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;
In the OP's case, this is redundant. As I said before, the static data
member shall already be instantiated by the explicit instantiation of
the class.
James Kanze's trick is useful to force the instantiation of the static
data member even if the class is *implicitly* instantiated. In this case
you suggestion doesn't help.
However, I agree that a statement like "®" is a bit too cryptic
(imagine an HTML expert surprised to see a registered trademark in C++
code :-D). Moreover, the absence of side-effects might tempt aggressive
compiler to optimize the statement away. Maybe wrapping the idiom inside
a function could make it more readable and avoid the problem. For example:
volatile void* ptr;
template <class T>
inline void force_instantiation_of(T& x) { ptr = &x; }
template <typename T>
class helper
{
public:
~helper() { force_instantiation_of(reg); }
private:
static type_record reg;
};
Notice that force_instantiation_of has a side effect so it can't be
optimized away. However this force_instantiation_of has a non-null cost.
Maybe we could propose a library function that does just that: force an
object to marked as "used" (in the sense that the linker can't strip it
away) without actually doing nothing. What do you think?
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]