CIS-255 Home http://www.c-jump.com/bcc/c255c/c255syllabus.htm

C++ Templates


  1. Templates
  2. Template user syntax
  3. Template syntax for classes
  4. More template syntax
  5. Template internals
  6. More template internals
  7. A useful template trick
  8. Default constructor behavior of C++ types
  9. Function templates
  10. Function template example
  11. Templates and friend
  12. Inheritance vs. templates
  13. Template philosophy
  14. Template arguments
  15. Default template arguments
  16. Template specialization
  17. More on template specialization
  18. Template specialization trick

1. Templates



2. Template user syntax



3. Template syntax for classes

  • Make this class declaration a template:

    
    template < typename ValueT >
    class Stack {
    public:
        void push( ValueT item );
    };
    
    
  • ValueT is the template parameter, standing in for the type.

  • When the user declares

    
        Stack< int > stack_i;
    
    
  • Template is instantiated for int, that is,
    ValueT becomes int:

    
    // Pseudocode:
    template < typename ValueT=int >
    class Stack {
    public:
        void push( int item );
    };
    
    

4. More template syntax



5. Template internals



6. More template internals



7. A useful template trick



8. Default constructor behavior of C++ types

  • More examples of the useful trick that we described:

    
    int x = int();       // x == 0
    
    double d = double(); // d == 0.0
    
    bool b = bool();     // b == false
    
    
    
  • 
    char* cp = char*();  // is a syntax error
    
    
  • However,

    
    #include <iostream>
    
    using namespace std;
    
    template< typename ValueT >
    class Thing {
    public:
        Thing< ValueT >()
        {
            ValueT dummy = ValueT();
            // dummy is zero if ValueT is a pointer:
            std::cout << static_cast< void* >( dummy );
        }
    };//class Thing
    
    int main()
    {
        Thing< char* > thing;
        return 0;
    }
    
    

9. Function templates



10. Function template example



11. Templates and friend



12. Inheritance vs. templates



13. Template philosophy



14. Template arguments



15. Default template arguments



16. Template specialization



17. More on template specialization



18. Template specialization trick