Created
March 20, 2017 14:37
-
-
Save dryman/ba63c238948b39af03674baae21cfc2f to your computer and use it in GitHub Desktop.
Polymorphism by GCC transparent union extension (works in clang as well)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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