繁体   English   中英

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

[英]Is it possible to check if a variable is of type struct?

假设我有以下结构:

struct A{
    int a;
} a;

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

如何检查bB型还是b型是A型?

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

在编译时:

#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);  

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

它就像一个怎样char可以代表一个字符,一个正数还是负数(或任何其他为此事)。 它取决于上下文以及程序员如何使用它。

否。与使用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')
{
    // ...
}

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

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

这个宏使用stringification用它的类型信息初始化每个结构:

 #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 *类型作为第一个参数在每个结构。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM