如何验证 void 指针 (void *) 是否是两种数据类型之一? [英] How to verify if a void pointer (void *) is one of two data types?

查看:22
本文介绍了如何验证 void 指针 (void *) 是否是两种数据类型之一?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个函数,我想在其中接受 2 个 type 参数.

  • 一个 string (char *)
  • 一个 结构,其中有 n 个元素.

为了实现这一点,我正在考虑使用一个简单的 void * 作为参数类型.但我不知道如何安全地验证参数是一种类型还是另一种类型.

解决方案

void* 的翻译是
亲爱的编译器,这是一个指针,没有关于此的额外信息.".

通常编译器比你(程序员)更了解,因为他更早得到的信息仍然记得,你可能已经忘记了.
但在这种特殊情况下,您更了解或需要更了解.在 void* 的所有情况下,信息都是可用的,但仅限于碰巧知道"的程序员.因此,程序员必须将信息提供给编译器 - 或者更好地提供给正在运行的程序,因为 void* 的一个优点是信息可以在运行时更改.
通常这是通过将信息通过附加参数提供给函数来完成的,有时通过上下文,即程序碰巧知道"(例如,对于每种可能的类型,都有一个单独的函数,无论调用哪个函数都暗示了该类型).

所以最后void*不包含类型信息.
许多程序员将其误解为我不需要知道类型信息".
但恰恰相反,使用 void* 增加程序员跟踪类型信息并将其适当地提供给程序/编译器的责任.>

I am writing a function where i would like to accept 2 types of parameters.

  • A string (char *)
  • A structure where there will be n number of elements.

And to achieve this i am thinking of using a simple void * as parameter type. But i do not know how to verify if the parameter is one type or the other, safely.

解决方案

The translation of void* is
"Dear compiler, this is a pointer, an there is no additional information for you on this.".

Usually the compiler knows better than you (the programmer), because of information he got earlier and still remembers and you might have forgotten about.
But in this special case, you know better or need to know better. In all cases of void* the information is available otherwise, but only to the programmer, who "happens to know". The programmer therefor has to provide the information to the compiler - or better to the running program, because the one advantage a void* has is that the information can change during runtime.
Usually that is done by giving the information via additional parameters to functions, sometimes via context, i.e. the program "happens to know" (e.g. for each possible type there is a separate function, whichever function gets called implies the type).

So in the end void* does not contain the type info.
Many programmers misunderstand this as "I don't need to know the type info".
But the opposite is true, the use of void* increases the responsibility of the programmer to keep track of the type info and provide it appropriatly to the program/compiler.

这篇关于如何验证 void 指针 (void *) 是否是两种数据类型之一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆