Type variable
Template:Short description In type theory and programming languages, a type variable is a mathematical variable ranging over types. Even in programming languages that allow mutable variables, a type variable remains an abstraction, in the sense that it does not correspond to some memory locations.
Programming languages that support parametric polymorphism make use of universally quantified type variables. Languages that support existential types make use of existentially quantified type variables. For example, the following OCaml code defines a polymorphic identity function that has a universally quantified type, which is printed by the interpreter on the second line:
<syntaxhighlight lang="ocaml">
- let id x = x;;
val id : 'a -> 'a = <fun> </syntaxhighlight>
In mathematical notation, the type of the function id is <math>\forall a.a \to a</math>, where <math>a</math> is a type variable.
Generic programming
In generic programming, a type parameter or template parameter is used to denote the type(s) that may be consumed. These type parameters are placeholders for types to be specified later, allowing for code to work with different types while remaining type-safe. Type parameters are typically written as a single capital letter.
<syntaxhighlight lang="java"> interface List<E> {
void add(E x); Iterator<E> iterator();
}
interface Map<K, V> {
V put(K key, V value); V get(Object key);
} </syntaxhighlight>
In C++, template parameters must be declared with the <syntaxhighlight lang="cpp" inline>typename</syntaxhighlight> (or <syntaxhighlight lang="cpp" inline>class</syntaxhighlight>) keyword.
In some languages, these can be specified to have default type parameters. For example, in C++: <syntaxhighlight lang="cpp"> template <typename T = int> class Box { private:
T value;
public:
explicit Box(T value):
value{value} {}
// ...
};
Box<double> b1(13.5); Box<> b2(5); // This is Box<int> </syntaxhighlight>
Some languages additionally offer a form of constraining these type parameters, called type classes. C++ offers concepts and <syntaxhighlight lang=cpp inline>requires</syntaxhighlight> clauses,[1] C#, Kotlin, and Rust offer <syntaxhighlight lang=csharp inline>where</syntaxhighlight> clauses,[2][3] while Java has <syntaxhighlight lang=java inline>extends</syntaxhighlight> and <syntaxhighlight lang=java inline>super</syntaxhighlight> qualifiers. Go interfaces also constrain a type such that it must implement certain methods.[4]
<syntaxhighlight lang="csharp"> using System;
public class MyGenericClass<T, U>
where T : IComparable<T>, allows ref struct where U : class, notnull, new()
{
// ...
} </syntaxhighlight>
Additionally, Java offers wildcard type parameters to allow for variances of any parametrisations of a generic type. These are denoted ?, for example <syntaxhighlight lang=java inline>List<?></syntaxhighlight>.[5] This exists in Kotlin as well, but denoted with * instead. In Rust, a generic type parameter can be left unspecified for the compiler to interpret using _, called an "inferred type" (for example <syntaxhighlight lang="rust" inline>Vec<_></syntaxhighlight>).[6]
In languages with dynamic typing, although type annotations may not be a core part of the language, some features may be provided to emulate them. For example, in Python, type variables can still be represented and specified using the class <syntaxhighlight lang=python inline>typing.TypeVar</syntaxhighlight>.[7]
<syntaxhighlight lang="python"> from typing import TypeVar
T: TypeVar = TypeVar('T')
def first_item(items: list[T]) -> T:
return items[0]
</syntaxhighlight>
In C++ and Rust and others with intricate template metaprogramming, template parameters may be non-types as well.
<syntaxhighlight lang="cpp"> using std::array;
template <typename T, size_t M, size_t N> class Matrix { private:
array<array<T, N>, M> data;
public:
Matrix() = default;
template <typename Self>
constexpr auto&& operator[](this Self&& self, size_t row, size_t col) {
return std::forward<Self>(self).data[row][col];
}
}; </syntaxhighlight>
See also
References
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- ↑ {{#invoke:citation/CS1|citation |CitationClass=web }}
- Generic programming
- Type theory
- Functional programming
- Dependently typed programming
- Programming language comparisons
- Articles with example C++ code
- Articles with example C Sharp code
- Articles with example Java code
- Articles with example OCaml code
- Articles with example Python (programming language) code
- Articles with example Rust code