Templates - C P P

Theory


  • Pass data type as a parameter so that we don’t need to write the same code for different data types
  • Templates are expanded at compiler time like macros, but compiler does type checking before expansion
  • Both function overloading and templates are examples of polymorphism features of OOP

Commands


  • template <typeName T> => Initialize
  • Function Template
        T variable(T var1) {
            // Statements
        }
        // Call a template function
        variable<dataType>(argument);
    
  • Class Template
        template <typename T> class className {
            // Statements
        }
        // Call a template class
        className<dataType> variable(argument);
    
  • Others
    • More than one argument
          template <class className3, class className2> class className1 {
              // Statements
          }
      
    • Specify a default value
          template <class className3, class className2 = dataType> class className1 {
              // Statements
          }
      
Share: