ILE C/C++ Programmer's Guide

Linkage

As shown in the following figure, the constructor function of the template is defined inline. Assume that the other functions are defined using separate function templates in the file stack.c:

Figure 319. Example of a Constructor Function that Is Defined Inline


template <class Item, int size>
   int Stack<Item,size>::operator << (Item item) {
     if (top >= size) return 0;
      stack[top++] = item;
      return 1;
   }
template <class Item, int size>
    int Stack<Item,size>::operator >> (Item& item)
   {
      if (top <= 0) return 0;
       item = stack[--top];
       return 1;
   }

Notes:

  1. The constructor has internal linkage because it is defined inline in the class template declaration. This means that the compiler generates the constructor function body in each compilation unit that uses an instance of the Stack class. In other words, each unit has and uses its own copy of the constructor.

  2. For the instance of the Stack class in the compilation unit, the compiler generates definitions for the following functions:

    Stack<item,size>::operator<<(item)
    Stack<item,size>::operator>>(item&)

    because there is explicit specialization.

If the class template is instantiated in the source file usrstack.cpp, that C++ program contains code similar to that shown in the following figure:

Figure 320. Example of a Constructor Function that Is Defined Externally



#include "stack.h"
#include "stack.c"
void Swap(int i&, Stack<int,20>& s)
{
int j;
s >> j;
s << i;
i = j;
}
Note:
The compiler generates the functions
Stack<int,20>::operator<<(int) and
Stack<int,20>::operator>>(int&) because both
those functions are used in the program, their defining templates are visible,
and no explicit specializations are seen.


[ Top of Page | Previous Page | Next Page | Table of Contents ]