Question

Generally I do the following:

if (msg.hasElement(BID_SIZE))
{
   bid_sz=msg.getElementAsInt32(BID_SIZE);
}

If I don't use check first using hasElement - then fields that don't exist will throw an error

Was it helpful?

Solution

Instead of using getElementAsInt32 use getValueAs:

Element field;
int err=msg.asElement().getElement(&field, BID_SIZE);
if (!err)
{
    int valerr=field.getValueAs(&bid_sz);  // will call getValueAs for the type of bid
}

This will avoid looking for BID_SIZE twice in the message, and will not throw when fields are not found.

Alternatively you can loop through all fields and check which field it is:

Element asElem=msg.asElement();
size_t num=asElem.numElements();
for (size_t i=0; i < num; ++i)
{
   Element field=asElem.getElement(i);
   Name field_name=field.name();
   if (field_name == BID_SIZE)
   {
       bid_sz=field.getValueAsInt32();
   }
   // check other fields
   // put more likely fields at the top   
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top