> In C, there are no (user-defined) generics
C has had generics since C11. I’ve got a clone of “the good parts” of the std C++ template library (vector, unordered_map, ...) laying around somewhere.
C has had generics since C11. I’ve got a clone of “the good parts” of the std C++ template library (vector, unordered_map, ...) laying around somewhere.
_Generic(x, type : value, ..., [default : value])
For a list of unique types, with an optional 'default' for any unrecognized type.You usually wrap the call to '_Generic' in a macro. For instance:
#define vec_push_back(vec, val) \
_Generic(&vec, \
vecint : vecint_push_back, \
vecdbl : vecdbl_push_back, \
default : assert_vwrap)(&vec, val)
Assuming that types 'vecint' and 'vecdbl' have been defined by the user. This does single-parameter parametric type dispatch. There's way to allow the user to use table-driven macros ('X-macros') to allow per-translation-unit definition of an arbitrary number of instantiations.The nice part, over C++, is that the generic instantiation is localized to a single translation-unit file, so you don't have to yell at the junior devs for instantiating templates without using an 'extern' construct.