Concept

Template (C++)

Summary
Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class declaration to reference via a generic variable another different class (built-in or newly declared data type) without creating full declaration for each of these different classes. The C++ Standard Library provides many useful functions within a framework of connected templates. Major inspirations for C++ templates were the parameterized modules provided by the language CLU and the generics provided by Ada. There are three kinds of templates: function templates, class templates and, since C++14, variable templates. Since C++11, templates may be either variadic or non-variadic; in earlier versions of C++ they are always non-variadic. A function template behaves like a function except that the template can have arguments of many different types (see example). In other words, a function template represents a family of functions. The format for declaring function templates with type parameters is: template declaration; template declaration; Both expressions have the same meaning and behave in exactly the same way. The latter form was introduced to avoid confusion, since a type parameter need not be a class until C++20. (It can be a basic type such as int or double.) For example, the C++ Standard Library contains the function template max(x, y) which returns the larger of x and y. That function template could be defined like this: template T max(T &a, T &b) { return a > b ? a : b; } This single function definition works with many data types. Specifically, it works with all data types for which > (the greater-than operator) is defined. The usage of a function template saves space in the source code file in addition to limiting changes to one function description and making the code easier to read. A template does not produce smaller object code, though, compared to writing separate functions for all the different data types used in a specific program.
About this result
This page is automatically generated and may contain information that is not correct, complete, up-to-date, or relevant to your search query. The same applies to every other page on this website. Please make sure to verify the information with EPFL's official sources.