Type-safe generic data structures in plain-old C?

后端 未结 10 2152
庸人自扰
庸人自扰 2020-12-04 08:23

I have done far more C++ programming than \"plain old C\" programming. One thing I sorely miss when programming in plain C is type-safe generic data structures, which are p

10条回答
  •  独厮守ぢ
    2020-12-04 08:47

    Option 1 is the approach taken by most C implementations of generic containers that I see. The Windows driver kit and the Linux kernel use a macro to allow links for the containers to be embedded anywhere in a structure, with the macro used to obtain the structure pointer from a pointer to the link field:

    • list_entry() macro in Linux
    • CONTAINING_RECORD() macro in Windows

    Option 2 is the tack taken by BSD's tree.h and queue.h container implementation:

    • http://openbsd.su/src/sys/sys/queue.h
    • http://openbsd.su/src/sys/sys/tree.h

    I don't think I'd consider either of these approaches type safe. Useful, but not type safe.

提交回复
热议问题