有几种方法可以解决。我敢肯定,其他人比我可能有其他人建议的更熟练。
- 选项 A:传递一个 void 指针和某种数据类型的指示,然后对其进行转换。
- 选项 B:将两个指针组合成一个并集并传递它。
- 选项 C:将类型和联合组合成一个结构并传递它
- 选项 D:使用更受尊重的替代方案来代替工会
一些示例代码...
enum DataType { TYPE_1, TYPE_2 };
struct Type1 { ... };
struct Type2 { ... };
union Data
{
void* addr;
struct Type1* type1;
struct Type2* type2;
}
struct Object
{
DataType type;
union Data data;
}
struct Thing
{
DataType type;
void* data;
}
void someFunc1( void* data, DataType type )
{
switch( type )
{
case TYPE_1:
{
struct Type1* type1 = (struct Type1*)data;
...
break;
}
case TYPE_2:
{
struct Type2* type2 = (struct Type2*)data;
...
break;
}
}
}
void someFunc2( union Data* data, DataType type )
{
switch( type )
{
case TYPE_1:
{
struct Type1* type1 = data->type1;
...
break;
}
case TYPE_2:
{
struct Type2* type2 = data->type2;
...
break;
}
}
}
void someFunc3( struct Object* object )
{
switch( object->type )
{
case TYPE_1:
{
struct Type1* type1 = object->data.type1;
...
break;
}
case TYPE_2:
{
struct Type2* type2 = object->data.type2;
...
break;
}
}
}
void someFunc4( struct Thing* thing )
{
switch( thing->type )
{
case TYPE_1:
{
struct Type1* type1 = (struct Type1*)thing->data;
...
break;
}
case TYPE_2:
{
struct Type2* type2 = (struct Type2*)thing->data;
...
break;
}
}
}
以另一种方式看待这个......如果你有一个只需要的方法,a
那么你可以做这样的事情......
void myFunc( int a ) { ... };
void someFunc3( struct Object* object )
{
myFunc( object->type == TYPE_1 ? object->data.type1->a : object->data.type2->a );
}
更好的是...修改函数以接受对象并仅在底部区分...
void myFunc( struct Object* object )
{
int* a;
switch( object->type )
{
case TYPE_1:
{
a = &object->data.type1->a
break;
}
case TYPE_2:
{
a = &object->data.type2->a;
break;
}
default:
{
abort();
}
}
// do work with a as though it were passed in as a pointer to int
if( object->type == TYPE_2 )
{
// do additional work with the b, c, d elements, etc.
}
}