liveBook · Manning

Type-generic interface

As explained in Modern C

Type-generic programming is a technique for providing one interface that selects or adapts behavior according to the types of its inputs.

A type-generic interface exposes one call form while selecting behavior from its arguments’ types. In C11, function-like macros combined with _Generic can choose among type-specific functions or expressions. section 16.6

Dispatching a floating-point function

A macro can map float to fabsf, long double to fabsl, and other types to fabs, then apply the selected function pointer to X. A two-argument minimum interface follows the same pattern, using (A)+(B) to determine the arithmetic type before calling minf, min, or minl. section 16.6

Type-generic interfaces are useful when a function alone cannot provide the required flexibility:

  • Select functions or values according to argument types. section 16.6
  • Provide compile-time argument checking and type mapping. section 16.0
  • Support interfaces whose behavior depends on the calling context or requires variable arguments. section 16.0
  • Avoid macros when an inline function already supplies a fixed, type-safe interface; unlike a naive square macro, an inline function evaluates count() only once. section 16.0

How Modern C covers it

How deep it goes
Explains _Generic selection and multi-argument dispatch, then demonstrates practical macro utilities without developing every language corner case.
Examples
Uses fabs dispatch, floating-point minimum, maximum-value selection, and tracing formats and conversions as concrete implementations.
What it assumes
Assumes familiarity with C function-like macros and inline functions while introducing _Generic as direct C11 language support.
What you can do after
Builds type-generic C11 macro interfaces that dispatch to typed functions or expressions while avoiding unnecessary macro evaluation hazards.
How it connects
Connects function-like macros with _Generic, inline functions, function pointers, type mapping, and the tgmath.h interfaces.

Also explained in

Compare how 2 books explain type-generic interface →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C. The section links point to the parts of the book it draws on.