Enforce strong type checking in C (type strictness for typedefs)

后端 未结 9 2370
遇见更好的自我
遇见更好的自我 2020-11-29 03:43

Is there a way to enforce explicit cast for typedefs of the same type? I\'ve to deal with utf8 and sometimes I get confused with the indices for the character count and the

相关标签:
9条回答
  • 2020-11-29 03:46

    For "handle" types (opaque pointers), Microsoft uses the trick of declaring structures and then typedef'ing a pointer to the structure:

    #define DECLARE_HANDLE(name) struct name##__ { int unused; }; \
                                 typedef struct name##__ *name
    

    Then instead of

    typedef void* FOOHANDLE;
    typedef void* BARHANDLE;
    

    They do:

    DECLARE_HANDLE(FOOHANDLE);
    DECLARE_HANDLE(BARHANDLE);
    

    So now, this works:

    FOOHANDLE make_foo();
    BARHANDLE make_bar();
    void do_bar(BARHANDLE);
    
    FOOHANDLE foo = make_foo();  /* ok */
    BARHANDLE bar = foo;         /* won't work! */
    do_bar(foo);                 /* won't work! */   
    
    0 讨论(0)
  • 2020-11-29 03:49

    You could do something like:

    typedef struct {
        unsigned int c_idx;
    } char_idx;
    
    typedef struct {
        unsigned int b_idx;
    } byte_idx;
    

    Then you would see when you are using each:

    char_idx a;
    byte_idx b;
    
    b.b_idx = a.c_idx;  
    

    Now it is more clear that they are different types but would still compile.

    0 讨论(0)
  • 2020-11-29 03:56

    What you want is called "strong typedef" or "strict typedef".

    Some programming languages [Rust, D, Haskell, Ada, ...] give some support for this at language level, C[++] does not. There was a proposal to include it into the language with the name "opaque typedef", but was not accepted.

    The lack of language support is really not a problem though. Just wrap the type to be aliased into a new class having exactly 1 data member, of type T. Much of the repetition can be factored out by templates and macros. This simple technique is just as convenient as in the programming languages with direct support.

    0 讨论(0)
  • 2020-11-29 03:59

    Use strong typedef as defined in BOOST_STRONG_TYPEDEF

    0 讨论(0)
  • 2020-11-29 04:00

    You asked about extensions. Jeff Foster's CQual is very nice, and I think it could do the job you want.

    0 讨论(0)
  • 2020-11-29 04:07

    In C, the only distinction between user-defined types that is enforced by the compiler is the distinction between structs. Any typedef involving distinct structs will work. Your major design question is should different struct types use the same member names? If so, you can simulate some polymorphic code using macros and other scurvy tricks. If not, you are really committed to two different representations. E.g., do you want to be able to

    #define INCREMENT(s, k) ((s).n += (k))
    

    and use INCREMENT on both byte_idx and char_idx? Then name the fields identically.

    0 讨论(0)
提交回复
热议问题