Hacker News new | past | comments | ask | show | jobs | submit login

My guess as someone who is not familiar with compiler internals is that the design of many compilers prevents them from implementing a typeof() operator without major changes to the way they analyze and store the parsed source code, so the standard writers decided not to include a feature that would not be widely implemented.

But, using _Generic(), one can do many of the things one would do with typeof(). For example, the max() example in [0] could probably be implemented using at most n^2 separate macros plus a _Generic() macro for each type, where n is the number of arithmetic types (though I think you'd still need GCC's statements within expressions in order to evaluate A and B only once).

I'm thinking something like this that combines the cbrt(X) example from the C1x spec [1] (ยง6.5.1.1 paragraph 5) with the gcc max() example, though I haven't tested it, and it could almost certainly be simplified by exploiting type promotion rules:

  #define max_ld_ld(A, B) ({long double _a = (A); \
      long double _b = (B); _a > _b ? _a : _b})
  
  #define maxld(A, B) _Generic((B), \
      long double: max_ld_ld, \
      int: max_ld_i, \
      /* etc. */ \
      )((A), (B))
  
  #define maxi(A, B) _Generic((B), \
      long double: max_i_ld, \
      int: max_i_i, \
      /* etc. */ \
      )((A), (B))
  
  #define max(A, B) _Generic((A), \
      long double: maxld, \
      int: maxi, \
      /* etc. */ \
      )((A), (B))
[0] http://gcc.gnu.org/onlinedocs/gcc/Typeof.html

[1] http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf

OT P.S. It is very annoying that Google has broken right-click+copy URL.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: