Skip to content

Instantly share code, notes, and snippets.

@dryman
Created March 20, 2017 14:37
Show Gist options
  • Save dryman/ba63c238948b39af03674baae21cfc2f to your computer and use it in GitHub Desktop.
Save dryman/ba63c238948b39af03674baae21cfc2f to your computer and use it in GitHub Desktop.
Polymorphism by GCC transparent union extension (works in clang as well)
typedef enum GenericType GenericType;
typedef struct A A;
typedef struct B B;
enum GenericType
{
TYPE_A = 0,
TYPE_B = 1,
};
struct A
{
GenericType type;
...
};
struct B
{
GenericType type;
...
};
union GenericPtr
{
GenericType* type;
A* A;
B* B;
} __attribute__((__transparent_union__));
void foo (GenericPtr ptr) {
switch(*ptr.type) {
case TYPE_A:
ptr.A->a_elements;
break;
case TYPE_B:
ptr.B->b_elements;
break;
default:
assert(false);
}
}
A* a;
B* b;
foo(a); // works
foo(b); // works
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment