在BLPAPI C++有没有办法避免使用hasElement或捕获错误

in the C++ BLPAPI is there a way to avoid using hasElement or catching errors

本文关键字:hasElement 错误 C++ BLPAPI 有没有      更新时间:2023-10-16

通常我执行以下操作:

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

如果我不使用 hasElement 先检查 - 那么不存在的字段将抛出错误

不使用getElementAsInt32请使用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
}

这将避免在消息中两次查找BID_SIZE,并且在找不到字段时不会抛出。

或者,您可以遍历所有字段并检查它是哪个字段:

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   
}