Skip to content
This repository was archived by the owner on Sep 30, 2024. It is now read-only.

Generic functions

David Tarditi edited this page Dec 7, 2018 · 5 revisions

Overview

Motivation

C has functions that operate over any pointer type, such as memcpy. These functions have parameters with the void pointer type. Type information is lost when the void pointer type is used. Any pointer type can be converted implicitly to or from the void pointer type. The conversion from the void pointer type could be incorrect, which could lead to memory corruption or an invalid memory read.

For example, a pointer to an integer on the stack could be converted to a void pointer, which could then be converted to a pointer to a struct with 4 pointer members. A subsequent use of the struct pointer could incorrectly write or read memory.

Functions that take or return void pointers can have the some problems, with incorrect conversions at calls to them or in their inner workings.

Type variables

Generic functions can also operate over any pointer type. However, instead of using the void pointer type, they use type variables to represent unknown types. A type variable can be used anywhere a type may be used when build types types or in declarations. Type variables, like the void pointer type, are incomplete types. They cannot be used as the type of a member or a variable. However, they can be used in pointer types. Type variables can be used to express constraints: if two arguments must point to values of the same type, the same type variable can be used.

Parameterizing functions by type variables

Generic function have type variables as additional parameters. When a generic function is called, types must be passed as additional arguments to the function. The type arguments determine the type at which the function is being used. Type parameters and arguments are purely compile-time constructs. They are not represented at run time.

Clone this wiki locally