Content deleted Content added
Tags: Mobile edit Mobile web edit |
Tags: Mobile edit Mobile web edit |
||
(3 intermediate revisions by the same user not shown) | |||
Line 213:
=====Technical overview=====
There are many kinds of templates, the most common being function templates and class templates. A ''function template'' is a pattern for creating ordinary functions based upon the parameterizing types supplied when instantiated. For example, the C++ Standard Template Library contains the function template <code>std::max(x, y)</code> that creates functions that return either ''x'' or ''y,'' whichever is larger. <code>max()</code> could be defined like this:
<syntaxhighlight lang="cpp">
Line 238:
</syntaxhighlight>
This works whether the arguments <code>x</code> and <code>y</code> are integers, strings, or any other type for which the expression <code>x
C++ templates are completely [[type safe]] at compile time. As a demonstration, the standard type <code>std::complex</code> does not define the <code>
Another kind of template, a ''class template
[[C++20]] introduces constraining template types using [[Concepts (C++)|concepts]]. Constraining the <code>max()</code> could look something like this:
<syntaxhighlight lang="cpp">
// in typename declaration:
template <std::totally_ordered T>
[[nodiscard]]
constexpr T max(T x, T y) noexcept {
return x < y ? y : x;
}
// in requires clause:
template <typename T>
requires std::totally_ordered<T>
[[nodiscard]]
constexpr T max(T x, T y) noexcept {
return x < y ? y : x;
}
</syntaxhighlight>
=====Template specialization=====
Line 698 ⟶ 717:
typeof (b) _b = (b); \
_a > _b ? _a : _b; })</syntaxhighlight>
The keyword <code>_Generic</code> is used in C preprocessor macros to automatically match the type of its parameter.
<syntaxhighlight lang="c">
#include <stdio.h>
#define type_of(x) _Generic((x), \
int: "int", \
float: "float", \
double: "double", \
char*: "string", \
default: "unknown")
int main(int argc, char* argv[]) {
printf("%s\n", type_of(42));
printf("%s\n", type_of(3.14f));
printf("%s\n", type_of(2.718));
printf("%s\n", type_of("hello"));
printf("%s\n", type_of((void *)0));
return 0;
}
</syntaxhighlight>
==See also==
|