Skip to content

Instantly share code, notes, and snippets.

@mdaisuke
Created June 29, 2014 00:50
Show Gist options
  • Save mdaisuke/d9b44d9d0ab030dd6da6 to your computer and use it in GitHub Desktop.
Save mdaisuke/d9b44d9d0ab030dd6da6 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <stdio.h>
typedef struct Base {
struct Type *type;
int x;
} Base;
typedef struct Type {
int (*func1)(Base *this);
int (*func2)(Base *this);
} Type;
int base_func1(Base *this) {return this->type->func1(this);}
int base_func2(Base *this) {return this->type->func2(this);}
int a_func1(Base *this) {return this->x * 10;}
int a_func2(Base *this) {return this->x * 11;}
static Type A = {
.func1 = a_func1,
.func2 = a_func2,
};
int b_func1(Base *this) {return this->x * 20;}
int b_func2(Base *this) {return this->x * 21;}
static Type B = {
.func1 = b_func1,
.func2 = b_func2,
};
Base *create(Type *type, int x)
{
Base *ret = malloc(sizeof(*ret));
ret->type = type;
ret->x = x;
return ret;
}
int main()
{
Base *o1 = create(&A, 1);
Base *o2 = create(&B, 1);
printf("%d %d\n", base_func1(o1), base_func1(o2));
printf("%d %d\n", base_func2(o1), base_func2(o2));
free(o1);
free(o2);
}
#include <stdlib.h>
#include <stdio.h>
struct Base;
typedef struct VTable {
int (*func)(struct Base *this);
} VTable;
typedef struct Base {
VTable *vtable;
int x;
} Base;
int base_func(Base *this) {return this->vtable->func(this);}
Base *base_new(VTable* vtable, int size, int x)
{
Base *ret = calloc(1, size);
ret->vtable = vtable;
ret->x = x;
return ret;
}
typedef struct A {
Base base;
} A;
int a_func(Base *this) {return this->x * 10;}
static VTable A_VTable = {
.func = a_func,
};
A *a_new(int x)
{
return (A*)base_new(&A_VTable, sizeof(A), x);
}
typedef struct B {
Base base;
int y;
} B;
int b_func(Base *base)
{
B *this = (B*)base;
return base->x * 20 + this->y;
}
static VTable B_VTable = {
.func = b_func,
};
B *b_new(int x)
{
B *ret = (B*)base_new(&B_VTable, sizeof(B), x);
ret->y = x * 2;
return ret;
}
int main()
{
Base *o1 = (Base*)a_new(1);
Base *o2 = (Base*)b_new(1);
printf("%d %d\n", base_func(o1), base_func(o2));
free(o1);
free(o2);
}
#include <stdlib.h>
#include <stdio.h>
typedef struct Base {
char (*func)();
} Base;
static char a_func() { return 'A'; }
static char b_func() { return 'B'; }
static Base *create(char (*func)())
{
Base *ret = malloc(sizeof(*ret));
ret->func = func;
return ret;
}
int main()
{
Base *o1 = create(a_func);
Base *o2 = create(b_func);
printf("%c %c\n", o1->func(), o2->func());
free(o1);
free(o2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment