4 ms·
Would it be possible to add C++'s implementation to C, or does it rely on other C++ features that C doesn't already support?
by saghm 8y ago
Would it be possible to add C++'s implementation to C, or does it rely on other C++ features that C doesn't already support?
- whyever 8y agoC does not have `auto`, so you couldn't store closures in local variables.
- v_lisivka 8y agoIn C, you can use typeof(). #define max(a,b) \ ({ typeof (a) _a = (a); \ typeof (b) _b = (b); \ _a > _b ? _a : _b; }) https://gcc.gnu.org/onlinedocs/gcc/Typeof.html https://gcc.gnu.org/onlinedocs/gcc/Typeof.html
- wahern 8y agotypeof is supported by everything[1] except the C standard. It was rejected in the 1990s and nobody on the committee seems to want to revisit the decision. To be fair, typeof is not as useful without statement expressions (`({ ... })`), and statement expressions aren't as widely supported. [1] All the major compilers support it (clang, GCC, IBM, Intel, Microsoft, Solaris, etc), plus or minus underscores in the identifier.
- Longhanks 8y agoYou’re not wrong, but C has __auto_type (at least GCC and clang support it, no idea about MSVC): https://gcc.gnu.org/onlinedocs/gcc/Typeof.html https://gcc.gnu.org/onlinedocs/gcc/Typeof.html
- int_19h 8y agoIt's a language extension, not standard C.
- aaaaaaaaaab 8y agoYes: classes. Every closure is an anonymous class in C++.
- calebh 8y agoC++ closures are a bit weird in that you have to specify how the captured data needs to be captured (either by reference or by copy). How the data is handled also depends on the implementation of std::function (if you decide to wrap your lambdas in that). It's possible that the implementation for std::function actually makes a reference-counted heap allocation every time a new closure is created. Anyway, the result is a lot of complexity that would be impossible to shoe-horn into C.