Hi All,
Considering the following code:
[SNIP list said:
I do not understand why the compiler does not complain when encountered with std::list<A>
when A has not been fully defined.
Could someone please explain to me when the compiler actually does the template expansion,
and is this method of using incomplete types as template arguments safe for all compliant
compilers?
In general it is undefined behaviour to instantiate any standard
container type with an incomplete type parameter. However, it has also
been shown that an implementation of the standard library can
carefully be written so that it will work with an incomplete type -
the main things to do are to no have any nested types, e.g. make
vector::iterator a typedef for a non-nested type.
To understand why, you need to know a little bit about implicit
instantiation. A class template specialization isn't instantiated
until it is used in a context that requires a completely defined
object type. So:
typedef mytemplate<int> t; //no instantiation
mytemplate<int> t; //no instantiation
sizeof(mytemplate<int>); //instantiation
mytemplate<int> t; //instantiation, possibly also of default
constructor
Now, when a class template definition is instantiated, any types that
need to be complete in the class definition are also instantiated.
e.g.
template <class T>
struct Foo
{
Bar<T> bar; //member, so instantiated
Baz<T>* baz; //pointer, so not instantiated
class Inner //member, so instantated
{
char array[sizeof(Baz<T>)]; //Baz<T> instantiated
};
};
So once you understand those rules, consider how std::list might be
implemented (ignoring the allocator parameter)
template <class T>
class list
{
struct Node
{
//boom, requires T to be complete
//when list<T> is instantiated
T value;
Node* prior;
Node* next;
};
//...
};
If you take the node type out, then you have:
template <class T>
struct ListNode
{
T value;
ListNode* prior;
ListNode* next;
};
template <class T>
class list
{
//doesn't instantiate ListNode<T> when list<T> is instaniated
typedef ListNode<T> node_t;
//doesn't instantiate ListNode<T>
node_t* node;
//... etc
};
GCC allows use of all containers with incomplete types. Dinkumware
have finally updated their library to do the same, and VC7.1 benefits.
Many other compilers (including earlier versions of MSVC) don't allow
incomplete types. Perhaps a future standard will guarantee that
containers can be instantiated with incomplete types, but don't hold
your breath.
Tom