lundi 29 janvier 2018

Looking for a clean way to use dynamic type declaration when accessing information in a union

I'm wrote some code today to access information in a very annoying hierarchy of classes. The code seems very ugly and repetitive for what I need to do, but I cannot figure out how to simplify it. I think the key would be the ability to declare types at runtime. I tried to find a better solution with auto, but I am unable to come up with anything.

I receive a message and need to determine if a sensor has been deployed. An value called the discriminant holds an enumerated value of the sensor type. Using that information I have to access a Union composed of many different sensors, selecting the correct one, and iterate through an array of utilization states looking for a value which represents deployed.

The classes would be near impossible to replicate but I write some psudo-code down below representing my current solution to the problem.

  SomeNamespace::Sensor_UE sensorType = message->data.sensingSystem.sensor.discriminant;
  bool dropMessage = true;
  if(message->data.sensingSystem.isValid)
  switch(sensorType)
  {
    case sensorType1:
    sensorType1 *sensor = &(message->data.sensingSystem.sensor.sensorType1)
    if(sensor->isValid)
      for(int i = 0; i < AnotherNamespace::ConstantsStruct::MaxUtilizationStates; i++)
      {
        if(sensor->utilizationState[i].value == YetAnotherNamespace::UtilizationStates::deployed)
        {
          dropMessage = false;
        }
      } 
  }

The switch statement below repeats with a dozen or so iterations of practically the same code. The only difference is the declaration and initiation of the sensor pointer. I would really like to get everything else outside the switch statement but since I have to declare the value based on the value of the sensorType enum I'm not sure if there is a way to do this. I would prefer not to use pointer math or c type casts as that stuff generally gets frowned upon unless absolutely necessary. Any thoughts would be appreciated.

Aucun commentaire:

Enregistrer un commentaire