Variant
Description
Declare a by-value tagged-union sum type N over the listed payload types. Emits a per-variant tag enum enum N##_Tag with one namespaced constant N##_<T> per type, the tagged union, and a static inline N N##_from_<T> constructor per type. No global registration – matchable directly with Match / When(N, T).
Usage example (from documentation)
Variant(Number, int, float, double);
Number n = Number_from_int(7);
// match with: Match(n) { When(Number, int, x) { ... x ... } ... }
Success
Defines enum N##_Tag { N_<T>, ... }, typedef struct { enum N##_Tag tag; union { T as_<T>; ... } u; } N;, and a typed constructor per payload. A trailing ; after the macro is required and consumed.
Failure
Macro cannot fail. More than 256 payloads is a compile error (the foreach ceiling). Payload type names must each be a single token; compound types must be typedef-d first.
Usage example (Cross-references)
Usage examples (Cross-references)
- In
Http.c:317:
return "505 HTTP Version Not Supported";
case HTTP_RESPONSE_CODE_VARIANT_ALSO_NEGOTIATES :
return "506 Variant Also Negotiates";
case HTTP_RESPONSE_CODE_INSUFFICIENT_STORAGE :
return "507 Insufficient Storage";- In
Variant.c:9:
// Self-contained variants -- no global registration; two variants sharing a
// payload type do not collide.
Variant(Number, int, double);
Variant(Cell, int, char);
Variant(Tri, int, float, char);- In
Variant.c:10:
// payload type do not collide.
Variant(Number, int, double);
Variant(Cell, int, char);
Variant(Tri, int, float, char);- In
Variant.c:11:
Variant(Number, int, double);
Variant(Cell, int, char);
Variant(Tri, int, float, char);
// ---------------------------------------------------------------------------
- In
Variant.c:125:
int main(void) {
WriteFmt("[INFO] Starting Generics.Variant tests\n\n");
TestFunction tests[] = {
test_variant_construct_and_match,- In
Variant.c:140:
int total = sizeof(tests) / sizeof(tests[0]);
int deadend = sizeof(deadend_tests) / sizeof(deadend_tests[0]);
return run_test_suite(tests, total, deadend_tests, deadend, "Generics.Variant");
}- In
Generics.h:22:
#include <Misra/Generics/TypeMatch.h>
#include <Misra/Generics/Variant.h>
#endif // MISRA_GENERICS_H
Last updated on