I'm less familiar with C than I am with C++, and right now I have a
problem with many structs I have defined where using C++ inheritance
classes would be perfect. For the functions that don't use any
variables unique to a specific species of this group of structs, is
there any way to avoid having to simply write multiple, almost
identical functions that only differ in the types of its arguements
and local variables?
One way is a technique known as "discriminated unions". This is one way of
achieving run-time polymorphism, which may be more than you need, but it
may just end up being the least of several evils in this case.
On the other hand, if each struct you're working with has exactly the same
layout, you /may/ be able to get away with casting to enable a uniform
naming scheme. Without more specific details on your structs and what
you're trying to do with them, I can't really say.
Here's the example of discriminated unions, anyway, in case that's of any
use (and these all have a /different structure/):
#include <stdio.h>
enum { TYPE1, TYPE2, TYPE3 /* ,... */ };
struct type1 {
int x;
long c;
};
struct type2 {
double y;
};
struct type3 {
char a;
double b;
};
struct master {
int type;
union {
struct type1 t1;
struct type2 t2;
struct type3 t3;
/* ... */
} u;
};
typedef struct master master;
void process(master *m)
{
switch (m->type)
{
case TYPE1:
printf("type1: x = %d\n", m->u.t1.x);
break;
case TYPE2:
printf("type2: y = %f\n", m->u.t2.y);
break;
case TYPE3:
printf("type3: a = %c\n", m->u.t3.a);
break;
default:
printf("Bad type\n");
}
}
int main()
{
master m1, m2, m3;
m1.type = TYPE1;
m1.u.t1.x = 42;
m2.type = TYPE2;
m2.u.t2.y = 2.23606679774;
m3.type = TYPE3;
m3.u.t3.a = 'z';
process(&m1);
process(&m2);
process(&m3);
return 0;
}
Output:
type1: x = 42
type2: y = 2.236067
type3: a = z
-leor