David Lindauer <ca*****@bluegrass.net> wrote i
Eric wrote: I have a template class that instantiates a variable of the template
parameter type as follows:
template <class T>
struct TemplateClass
{
T t;
};
struct TestClass
{
int x;
static TemplateClass<TestClass> v2;
};
That definitely does compile with the borland compiler, but I am
wondering what the rules are for this since TestClass isn't
fully defined when the template is instantiated? Same thing
doesn't work without the 'static' - but doing the equivalent without
a template doesn't work at all.
Good question...there are a number of slightly tricky things in play
here.
First, you may or may not have noticed that TestClass::v2 isn't
defined. That means that if you write a program that tries to access
TestClass::v2, you'll get a link error. (The *compiler* won't
complain, because TestClass::v2 might be defined in some other
translation unit.)
Next, you probably want to know the point of instantiation of
TemplateClass<TestClass>. There's no explicit instantiation, so the
rules for implicit instantiation apply (14.7.1). In particular, "the
class template specialization is implicitly instantiated when the
specialization is referenced in a context that requires a
completely-defined object type or when the completeness of the class
affects the semantics of the program."
9.4.2/2 says that a static data member may be declared with an
incomplete type, so the declaration, by itself, does not cause the
instantiation of TemplateClass<TestCase>.
Of course, the *definition* of TestClass::v2 *will* require a complete
type, so that may be the point of instatiation. (It will be, unless
something else forces the instantiation first.)
Naturally, the definition of TestClass::v2 will follow the full
declaration of TestClass, so TestClass will be complete, and there
will be no difficulty instantiating TemplateClass<TestClass>, even
though it contains a non-static data member of type TestClass.
Unless I'm wrong.... :-)