Author Topic: C11's _Generic  (Read 3886 times)

lerno

  • Full Member
  • ***
  • Posts: 247
    • View Profile
C11's _Generic
« on: October 25, 2018, 11:19:44 AM »
I suggest support for a version of _Generic.

The functionality is simple:

Code: [Select]
#define to_num(x) _Generic((x), int:0, char:1, long:2, default:3)

int i = 2;
long x = 100;   

printf("%d / %d / %d\n", to_num(i), to_num(x), to_num(&x));

This prints "1 / 2 / 3"

Basically _Generic acts like a switch:

switch ("type of x") {
   case "int": 0
   case "char": 1
   case "long": 2
   default: 3
}

Because the non-taken paths aren't evaluated, this rather powerful in expressing "overloaded" math functions (to take an example)

This could be used to implement overloads for operators as well.