Template

Why Trust Techopedia

What Does Template Mean?

A template is a C++ programming feature that permits function and class operations with generic types, which allows functionality with different data types without rewriting entire code blocks for each type.

Advertisements

Templates are a valuable utility in C++, especially when used with operator overloading and multiple inheritance. Templates reduce the effort associated with coding different data types to a single set of code and reduce debugging efforts.

Techopedia Explains Template

C++ provides the following two types of templates used to implement general constructs, such as lists, queues, vectors and stacks:

  • Class template: Resembles a regular class definition but is prefixed by the following: template <class typename="" identifier="">, followed by the class body declaration, including member data and functions. Class template member function declarations and definitions are in the same header file. C++ class templates are best suited to container classes.
  • Function template: Implemented through template parameters, which is a special parameter type used to pass a type as a function argument. Thus, functionality may be adapted to more than one type or class without repeating the entire code. The format to declare a function template with a type parameter is either template <class identifier> function_declaration or template <typename identifier> function_declaration. There is no difference between the class and typename keywords.

Templates generally require type-checking at compile-time.

Template-generated code may be overriden by providing special definitions for specific types, which is known as template specialization. A special version of a function for a given set of template arguments is known as explicit specialization. A class template specialized by a subset of its parameters is known as a partial template specialization. Full specialization occurs f every parameter is specialized.

Advertisements

Related Terms

Margaret Rouse
Technology Expert
Margaret Rouse
Technology Expert

Margaret is an award-winning technical writer and teacher known for her ability to explain complex technical subjects to a non-technical business audience. Over the past twenty years, her IT definitions have been published by Que in an encyclopedia of technology terms and cited in articles by the New York Times, Time Magazine, USA Today, ZDNet, PC Magazine, and Discovery Magazine. She joined Techopedia in 2011. Margaret's idea of a fun day is helping IT and business professionals learn to speak each other’s highly specialized languages.