简体   繁体   English

Typedef中的C / C ++前向声明

[英]C/C++ forward declaration in typedef

Looking at the OpenCL header file I see: 查看OpenCL头文件,我看到:

typedef struct _cl_context * cl_context;

I understand that cl_context is a pointer to a forward declared struct _cl_context . 我知道cl_context是一个指向前向声明的struct _cl_context的指针。

From the perspective of a library designer, what are the advantages to doing this over: 从图书馆设计师的角度来看,这样做有什么好处:

typedef struct _cl_context cl_context;

Is it just so the API calls can take cl_context instead of cl_context* ? 它只是这样API调用可以使用cl_context而不是cl_context* But if so, why not just do: 但如果是这样,为什么不这样做:

typedef void *cl_context;

This is a typesafe way of building APIs, without exposing the internals of a type (which are implementation details). 这是一种构建API的类型安全方法,不会暴露类型的内部(这是实现细节)。

typedef struct _cl_context* cl_context;

Doing this allows you to define the API using the type cl_context, without defining the struct _cl_context anywhere in the header files. 这样做可以使您使用cl_context类型定义API, 而无需在头文件中的任何位置定义struct _cl_context。 It is clear to all that the functions take this type (a pointer) as an argument, but the user is not burdened with the details of struct _cl_context. 所有人都清楚函数将这种类型(指针)作为参数,但是用户不必负担struct _cl_context的细节。 The struct can be defined elsewhere (in the .c file or a private header). 可以在其他地方(在.c文件或专用头文件中)定义该结构。

The other approach you mention is: 您提到的另一种方法是:

typedef void* cl_context;

This is used as well many places. 这也被用于许多地方。 But requires typecasting in the code all over the place, before the argument can be interpreted. 但是,在解释参数之前,需要在整个代码中进行类型转换。 And it is not typesafe. 它不是类型安全的。 The user can pass in any pointer as the argument, and the compiler will accept it - which is not a good thing. 用户可以传入任何指针作为参数,编译器将接受它 - 这不是一件好事。 using the real type ensures some safety in terms of arguments being passed back and forth. 使用真实类型可确保在来回传递的参数方面具有一定的安全性。

In C, when you declare a struct like: 在C中,当您声明一个结构时:

struct foo { };

To declare an instance of this struct, you would say: 要声明此结构的实例,您会说:

struct foo f;

Therefore C programmers tend to declare structs like: 因此,C程序员倾向于声明结构,如:

typedef struct foo { } foo;

As in, foo is a typedef for struct foo 就像在, foostruct foo的typedef

This requirement is gone for C++. 对于C ++,此要求已消失。

I don't think that typedef struct cl_context; 我不认为typedef struct cl_context; compiles. 编译。 Maybe you meant typedef struct _cl_context cl_context; 也许您是说typedef struct _cl_context cl_context; ?

Is it just so the API calls can take cl_context instead of cl_context*? 它只是这样API调用可以使用cl_context而不是cl_context *?

That typedef takes care of both that and eliminating the need to prepend your type declarations with struct . 该typedef既可以做到这一点,又可以避免在struct类型声明。

You would certainly not want to use typedef void *cl_context; 您当然不希望使用typedef void *cl_context; because then you lose type safety. 因为那样您会失去类型安全性。

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

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