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

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

问题描述

我正在编写一个函数,我想接受2个类型的参数。

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


  • A 字符串(字符*)

  • A 结构

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

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

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.

推荐答案

<$的翻译c $ c> void * 是

亲爱的编译器,这是一个指针,对此您没有其他信息。。

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

通常,由于编译器比您(程序员)更了解您,因为他早先得到的信息仍然记得,您可能已经忘记了。

但是在这种特殊情况下,您了解更多或需要了解更多。在 void * 的所有情况下,信息都是可用的,但仅适用于偶然会知道的程序员。为此,程序员必须将信息提供给编译器,或者更好地提供给正在运行的程序,因为 void * 的一个优点是信息可以在运行时更改。< br>
通常是通过附加的函数参数(有时是上下文)为信息提供信息,即程序碰巧知道(例如,对于每种可能的类型,都有一个单独的函数,无论调用哪个函数都意味着

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).

所以最后 void * 不包含类型信息。

许多程序员误解为我不需要知道类型信息。

但事实恰恰相反,使用 void * 增加,程序员有责任跟踪类型信息并将其适当地提供给程序/编译器。

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天全站免登陆