Templates

Index



Templates

  • Is a way of making generic functions or classes by specifying as a parameter the type (or types) of data upon the function or class operates.
  • This way we save lots of time and code by avoiding recode an specific class or function for each different type of data.
  • Generic functions can be over-riden by specialized functions.


    Generic Function Example
  • The better way to understand Templates is with a simple example
  • #include ≤iostream≥
    using namespace std;
    
    int min(int a, int b)
    {
        return(a≤b)?a:b;
    }
    
    int main()
    {
        int a=10, b=5;
        cout ≤≤ min(a,b) ≤≤ '\n';
        char p='A', q='Z';
        cout ≤≤ min(p,q) ≤≤ '\n';
        float z=1.91f, x=3.98f;
        cout ≤≤ min(z,x) ≤≤ '\n';
        return 0;
    }
        
    
  • This is the output:
    5
    A
    1.91
    
  • Now, let's see the template version:
    #include
    using namespace std;
    
    template ≤class T≥
    T min (T a, T b)
    {
        return (a ≤ b)?a:b;
    }
    
    int main()
    {
        in a=10, b=5;
        cout ≤≤ min(a,b) ≤≤ '\n';
        char p='A', q='Z';
        cout ≤≤ min(p,q) ≤≤ '\n';
        float z=1.91, x=3.98;
        cout ≤≤ min(z,x) ≤≤ '\n';
        return 0;
    }
    




    Generic Class Example

  • Ok, now is time to show how to use generic classes.
    // This function demonstrates a generic stack
    #include≤class StackType≥ class stack {
        StackType stck[SIZE]; //holds the stack
        int tos; // index of top-of-stack
    public:
        stack() { tos = 0; } // stack initialization
        void push(StackType ob); // push object on stack
        StackType pop(); // pop object from stack
    };
    // Push an object
    template ≤class StackType≥ void stack≤StackType≥::push(StackType ob) {
        if(tos == SIZE) {
            cout ≤≤ "Stack is full.\n";
            return;
        }
        stck[tos] = ob;
        tos++;
    }
    
    // Pop and object
    template ≤class StackType≥StackType stack ≤StackType≥::pop() {
        if(tos==0) {
            cout ≤≤ "Stack underflow.\n";
            return 0;
        }
        tos--;
        return stck[tos];
    }
    
    int main()
    {
        //Demonstrates character stacks
        stack≤char≥ stack1, stack2; //create two character stacks
    
        stack1.push('x');
        stack1.push('y');
        stack2.push('a');
        stack2.push('b');
    
        cout ≤≤ stack1.pop() ≤≤ " "
        cout ≤≤ stack2.pop() ≤≤ " "
    
        stack≤double≥ dstack1, dstack2; //create two double stacks
    
        dstack1.push(1.1);
        dstack1.push(2.2);
        dstack2.push(3.3);
        dstack2.push(4.4);
    
        cout ≤≤ dstack1.pop() ≤≤ " ";
        cout ≤≤ dstack2.pop() ≤≤ "\n";
    
        return 0;
    }