2 ms·
Funnily enough that's the most common pattern I see in my personal C code (for example, my little lisp interpreter - https://github.com/lelanthran/csl/blob/mast
by lelanthran 4y ago
Funnily enough that's the most common pattern I see in my personal C code (for example, my little lisp interpreter - https://github.com/lelanthran/csl/blob/master/src/parser/atom.c#L386 https://github.com/lelanthran/csl/blob/master/src/parser/ato...) but I still recommend using the `Generic` keyword in C.
For the next time I do a pattern like this, I'll be using `Generic` keyword to make the dispatch a compile-time match, not check at runtime.
- deleted 4y ago[deleted]
- KerrAvon 4y agoI think you may be disappointed. Every single time I've tried to use `_Generic`, I've found that it's more trouble than it's worth. They seem to have made it be useful for a very narrow case -- tgmath.h -- and not bothered to make it general enough to be applicable to a wide variety of things that you might like to use it with.
- jesse__ 4y agoCan you elaborate slightly on how you're planning on using _Generic to turn runtime dispatches into compile time ones? I'm not quite putting together how you can do that.
- lelanthran 4y agoThe example from the wikipedia page for C11 (https://en.wikipedia.org/wiki/C11_(C_standard_revision)#Changes_from_C99 https://en.wikipedia.org/wiki/C11_(C_standard_revision)#Chan...) is compile time determination of the function to call: #define cbrt(x) _Generic((x), long double: cbrtl, \ default: cbrt, \ float: cbrtf)(x) In code you'll write `cbrt(foo)` and the correct function will be called for the type of foo. As I understand it, the `_Generic` selection is performed at compile time.
- JonChesterfield 4y agoRecommend `__attribute__((overloadable))` instead of _Generic. The former opts into C++ style name mangling, which is a bit of a mess in C, but interacts well with `static` as forwarding wrappers in a header. The latter is a ridiculous mess invented by the C committee.
- ablob 4y agoThe latter does not require any name mangling. Any function that is called, was first created by the programmer. You might not like it, but it certainly fits any C code that wants to interface with other languages. Furthermore, I could only find this feature in the clang-compiler and references to it outside of the online-docs in gcc.