#include <stdio.h>
#define METHOD_DECLARE(run) typeof(&run) run
void run(void) { }
void runA(void) { puts(__func__); }
void runB(void) { puts(__func__); }
typedef struct Base
{
METHOD_DECLARE(run);
} Base;
typedef struct A
{
METHOD_DECLARE(runA);
int age;
} A;
typedef struct B
{
METHOD_DECLARE(runB);
char name[12];
} B;
void Process(Base *bs)
{
//多态
bs->run();
}
int main(int argc, char **argv)
{
A a = {runA, 12};
B b = {runB, "dwad"};
Base *bs = (Base *)&a;
Process(bs);
bs = (Base *)&b;
Process(bs);
return 0;
}
当然以上有局限性,还有就是内存对齐的问题需要注意