指向结构成员? [英] Point to a struct member?

查看:51
本文介绍了指向结构成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 typedefined struct:

I have the following typedefined struct:

typedef struct
{
    uint8_t u8Byte1;             // This byte takes the needed values sometimes
    uint8_t u8Byte2;             // Not used
    uint8_t u8Byte3;             // This byte takes the needed values the other times
    uint8_t u8Byte4;             // Not used
} tstrMapMetadata;

我有一个线程来填充(使用来自传感器的数据)这个结构并使用它的一个值:

And I have a thread that fills (with data from a sensor) this struct and uses one of its values:

while(true)
{
  tstrMapMetadata * pstrMapMetadata = something();
  
  if(pstrMapMetadata->u8Byte1 == SOMETHING) //<---- this line
  {
    //Do something special 
  }
}

但现在我有一个 condition(线程期间的常量),我希望用 u8Byte3 而不是 u8Byte1 完成标记行的比较代码>.

But now I have a condition (constant during the thread) in which I want the comparison of the marked line done with u8Byte3 instead of u8Byte1.

当然可以

if(((condition) ? pstrMapMetadata->u8Byte1 : pstrMapMetadata->u8Byte3) == SOMETHING) //<---- this line

但我会一直进行相同的比较.

有没有办法在声明之前指向结构的一个成员(它们是这样调用的吗?)?

Is there a way to point to one of the members (are they called like this?) of the struct before its declaration?

类似于(此代码当然不起作用,但可以让我了解我正在寻找的内容):

Something like (this code of course doesn't work but gives an idea of what I'm looking for):

uint8_t * coolPointer;
if(condition) 
{
  coolPointer = (someOperation)tstrMapMetadata(u8Byte1);
}
else
{
  coolPointer = (someOperation)tstrMapMetadata(u8Byte3);
}

while(true)
{
  tstrMapMetadata * pstrMapMetadata = something();
  
  if(coolPointer == SOMETHING) //<---- this line
  {
    //Do something special 
  }
}

谢谢!

推荐答案

成员指针:

uint8_t tstrMapMetadata::*member = condition ?
     &tstrMapMetadata::u8Byte1 :
     &tstrMapMetadata::u8Byte3;

while (true)
{
  tstrMapMetadata* pstrMapMetadata = something();
  
  if (pstrMapMetadata->*member == SOMETHING) // usage with ->*  ( .* for objet )
  {
    //Do something special 
  }
}

这篇关于指向结构成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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