Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stddef.h>
- #include <stdlib.h>
- #include "poly_types.h"
- /* declare a run-time polymorphic interface, 'poly' */
- iface_declare(poly,
- poly *(*new) (int);
- void (*set) (poly *, int);
- void (*print) (poly *);
- );
- /* Define some struct shared compatibly between 2 other types.
- *
- * Instances of which can be manipulated via the runtime polymorphic
- * 'poly'
- *
- */
- typedef struct {
- poly *poly_iface;
- int i;
- } shared;
- /* foo and bar, whatever sub-types of the above. Not going to setup
- * actual sub-types, just typedefs to test for now */
- typedef shared foo;
- typedef shared bar;
- iface_declare_casts(shared, poly, poly_iface);
- iface_declare_casts(foo, poly, poly_iface);
- iface_declare_casts(bar, poly, poly_iface);
- /* a common setter method */
- void poly_set (poly *, int);
- /* foo specific implementations */
- void foo_print (poly *);
- poly *foo_new (int);
- /* bar specific implementations */
- poly *bar_new (int);
- void bar_print (poly *);
- /* foo's vtable / operations */
- poly foo_ops = {
- .set = poly_set,
- .new = foo_new,
- .print = foo_print,
- };
- /* .. and bar's */
- poly bar_ops = {
- .set = poly_set,
- .new = bar_new,
- .print = bar_print,
- };
- void
- poly_set (poly *p, int i)
- {
- poly2shared(p)->i = i;
- }
- void
- foo_print (poly *p)
- {
- foo *p1 = poly2foo (p);
- printf ("foo: %u\n", p1->i);
- }
- poly *foo_new (int i)
- {
- foo *f = calloc (1, sizeof (foo));
- foo_poly_ops_set (f, &foo_ops);
- poly_set (foo2poly (f), i);
- return foo2poly (f);
- }
- poly *bar_new (int i)
- {
- bar *p = calloc (1, sizeof (bar));
- bar_poly_ops_set (p, &bar_ops);
- poly_set (bar2poly (p), i);
- return bar2poly (p);
- }
- void
- bar_print (poly *p)
- {
- bar *p2 = poly2bar (p);
- printf ("bar: %u\n", p2->i);
- }
- int main (void)
- {
- /* declare an array of differently typed objects */
- poly *polys [] = {
- foo_new (1),
- bar_new (2),
- };
- /* however, can easily call polymorphic functions on these objects */
- for (int i = 0; i < sizeof (polys) / sizeof(polys[0]); i++)
- {
- polys[i]->print (polys[i]);
- ifacef (poly, print, polys[i]);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement