Class template declarations and definitions (C++ only)

A class template must be declared before any instantiation of a corresponding template class. A class template definition can only appear once in any single translation unit. A class template must be defined before any use of a template class that requires the size of the class or refers to members of the class.

In the following example, the class template Key is declared before it is defined. The declaration of the pointer keyiptr is valid because the size of the class is not needed. The declaration of keyi, however, causes an error.

template  <class L> class Key;      // class template declared,
                                    // not defined yet
                                    //
class Key<int> *keyiptr;            // declaration of pointer
                                    //
class Key<int> keyi;                // error, cannot declare keyi
                                    // without knowing size
                                    //
template <class L> class Key        // now class template defined
{ /* ... */ };

If a template class is used before the corresponding class template is defined, the compiler issues an error. A class name with the appearance of a template class name is considered to be a template class. In other words, angle brackets are valid in a class name only if that class is a template class.

The previous example uses the elaborated type specifier class to declare the class template key and the pointer keyiptr. The declaration of keyiptr can also be made without the elaborated type specifier.

template  <class L> class Key;            // class template declared,
                                          // not defined yet
                                          //
Key<int> *keyiptr;                        // declaration of pointer
                                          //
Key<int> keyi;                            // error, cannot declare keyi
                                          // without knowing size
                                          //
template <class L> class Key              // now class template defined
{ /* ... */ };

Related information