Skip to content

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)
                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";
    // 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);
    // payload type do not collide.
    Variant(Number, int, double);
    Variant(Cell, int, char);
    Variant(Tri, int, float, char);
    Variant(Number, int, double);
    Variant(Cell, int, char);
    Variant(Tri, int, float, char);
    
    // ---------------------------------------------------------------------------
    
    int main(void) {
        WriteFmt("[INFO] Starting Generics.Variant tests\n\n");
        TestFunction tests[] = {
            test_variant_construct_and_match,
        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");
    }
    
    #include <Misra/Generics/TypeMatch.h>
    #include <Misra/Generics/Variant.h>
    
    #endif // MISRA_GENERICS_H
Last updated on