函数参数中的按位或 (|)
我想知道如何做到这一点:
func(param1|param2|param3)
然后在函数中提取这些值,我在多个函数中看到了这一点,或者这样做更好:
func(param1, ...)
?
我正在尝试在 C++ 中执行此操作,并且我正在考虑将函数的参数作为枚举中的值。
我该如何解决这个问题?
I was wondering how to do this:
func(param1|param2|param3)
and then extract those values in the function, I have seen this in multiple functions, or is it better to do this:
func(param1, ...)
?
I am trying to do this in C++, and I was thinking of having the parameters to the function as values in a enum.
How do I solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Param1、param2、param3 通常被定义为不同位打开的数字。
|
是按位替代运算符,这意味着它适用于单独的位。例如:
当您将参数传递给函数时,您会对之前定义的参数进行按位替代。
在函数中,您不进行分解,而是使用按位连接检查指定位是否已设置:
Param1, param2, param3 are usually defined as a numbers with different bits turned on.
|
is an operator of bitwise alternative, that means it works on separate bits.In example:
When you pass an argument to function you make a bitwise alternative of earlier defined params.
In function, you don't make a decomposition, but check if a specified bit is set on, using bitwise conjunction:
假设您有独立位(2 的幂)的值,例如:(
或等效的
enums
或const int
值,具体取决于您想要如何执行它们 - 我'使用#define
只是因为这是我习惯的),您可以将它们传递为:然后您提取它们,例如:
对于单位说明符,您可以得到不用
if (bitmask & IS_ON)
形式,但您需要全面检查您的说明符是否可能是多位值(例如 0 到 7 的三位音量级别)。Assuming you have the values as independent bits (powers of two) like:
(or the equivalent
enums
orconst int
values, depending on how you want to do them - I've used#define
simply because it's what I'm used to), you can pass them as:Then you extract them with something like:
For single-bit specifiers, you can get away with the
if (bitmask & IS_ON)
form but you need the full check if your specifiers may be multi-bit values (like a three-bit volume level of 0 through 7, for example).这是一个关于如何使用任意按钮类型创建“MessageBox”函数的有用示例:
This is an useful example to how create "MessageBox" function with arbitrary button types :