Skip to content

Instantly share code, notes, and snippets.

@chuntaro
Created June 22, 2019 04:54
Show Gist options
  • Select an option

  • Save chuntaro/f245e4f70e9ea8769ab3b1fcee3f5c1f to your computer and use it in GitHub Desktop.

Select an option

Save chuntaro/f245e4f70e9ea8769ab3b1fcee3f5c1f to your computer and use it in GitHub Desktop.
C 言語でオブジェクト指向(案)
#include <stdio.h>
#include <stdlib.h>
typedef struct _Base {
int foo;
} Base;
void base_print_foo(const Base* base) {
printf("foo -> %d\n", base->foo);
}
typedef struct _Derived {
Base base;
int bar;
} Derived;
// 以下は、自前のプリプロセッサで自動生成する
static inline void derived_print_foo(const Derived* derived) {
base_print_foo(&derived->base);
}
#define print_foo(X) _Generic((X), \
Base*: base_print_foo, \
Derived*: derived_print_foo)(X)
// 自動生成ここまで
int main()
{
Base* base = malloc(sizeof(Base));
base->foo = 1;
Derived* derived = malloc(sizeof(Derived));
derived->base.foo = 2;
derived->bar = 3;
// 今までは↓ちょっと冗長…
// base_print_foo((Base*)derived);
// or
// base_print_foo(&derived->base);
// これからは↓スッキリ!
print_foo(base);
print_foo(derived);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment