是否可以检查变量是否为struct类型?

时间:2012-06-05 20:13:12

标签: c

假设我有以下结构:

struct A{
    int a;
} a;

struct B{
    A a;
    int b;
} b;

如何检查bB类型还是b属于A类型?

6 个答案:

答案 0 :(得分:11)

你的意思是在运行时,假设void *指向一个或另一个?不幸的是,这是不可能的; C没有任何类型的运行时类型信息机制。

答案 1 :(得分:2)

在编译时:

#define WARN_IF_DIFFERENT_STRUCT_TYPE_1(T, o) do { \
    T temp = (o);                                  \
    (void) temp;                                   \
} while (0)

示例:

struct B b;
/* will warn if b is not of struct A type */
WARN_IF_DIFFERENT_STRUCT_TYPE_1(struct A, b);  

使用typeof GNU扩展名将两个对象作为宏参数传递:

#define WARN_IF_DIFFERENT_STRUCT_TYPE_2(o1, o2) do { \
    typeof(o1) temp = (o2);                          \
    (void) temp;                                     \
} while (0)   

示例:

struct A a;
struct B b;
/* will warn if a and b are not the same struct type */
WARN_IF_DIFFERENT_STRUCT_TYPE_2(a, b);  

答案 2 :(得分:0)

就C而言,数据只是一串位。如何使用和解释数据取决于程序员。

就像char如何表示一个角色,一个正数或一个负数(或其他任何事情)。这取决于上下文以及程序员如何使用它。

答案 3 :(得分:0)

没有。与使用vtable在运行时维护类型关联的C ++不同,C不提供运行时类型检查的方法。

可能的解决方法是将类型标识符指定为结构的第一个元素:

struct A {
    int type;
    int a;
} a; a.type = 'A';

struct B {
    int type;
    A a;
    int b;
} b; b.type = 'B';

// Now, given a (void*) pointer `ptr`, of either `A` or `B`...
if ( *(int*)ptr == 'A')
{
    // ...
}
elseif ( *(int*)ptr == 'B')
{
    // ...
}

答案 4 :(得分:0)

如果您要编写自己的类型检查机制,我建议您编写宏来为您填写类型字段。

typedef struct A {
   void *type;
   int a; 
} A;

这个宏使用字符串化来初始化每个结构的类型信息:

 #define InitializeType(ptr, type) \
      ((ptr)->type == (void *)(#type ## __FILE__ ##))
 #define IsType(ptr, type)      \
      ((ptr)!=NULL && (ptr)->type != (void *)(#type ## __FILE__ ##))

它使用包含结构名称及其所在文件的字符串填充类型字段。在多个源文件中可以有两个具有相同名称的结构,但是不能使用两个结构同一个源文件中的相同名称,因此包含了初始化类型的源文件的名称的原因。然后你会像这样使用它们:

 A alpha;
 InitializeType(&alpha, A);
 IsType(&alpha, A);

但有几个问题;你必须使用字符串池编译器标志,你必须在“类”中封装你的结构,以便类型检查和初始化本地化到包含私有结构的源文件,你必须有void *类型作为第一个参数在每个结构。

答案 5 :(得分:-2)

你可以破解它吗?如果真的有必要,你只有几个结构。

struct A{
    int a;
    int identifer = 0;
} a;

struct B{
    A a;
    int b;
    int identifer = 1;
} b;

如果您的代码可以像

那样
if object->identifer == 0 
     bla bla bla
相关问题