优化一下下面代码if(vsomeip::message_type_e::MT_REQUEST == _message->get_message_type()) { std::shared_ptr<vsomeip::message> its_response = vsomeip::runtime::get()->create_response(_message); if(TBOX_SERVICE_ID_LOCATION == _message->get_service()) { _location_service_response_map.insert(pair<uint16_t, std::shared_ptr<vsomeip::message>>(_message->get_method(), its_response)); } else if(TBOX_SERVICE_ID_TBS == _message->get_service()) { _tbox_service_response_map.insert(pair<uint16_t, std::shared_ptr<vsomeip::message>>(_message->get_method(), its_response)); } else if(TBOX_SERVICE_ID_RESV_UPDATE == _message->get_service()) { _resvUpdate_service_response_map.insert(pair<uint16_t, std::shared_ptr<vsomeip::message>>(_message->get_method(), its_response)); } else if(TBOX_SERVICE_ID_XCALL_VLAN04 == _message->get_service()){ _response_map.insert(pair<uint16_t, std::shared_ptr<vsomeip::message>>(_message->get_method(), its_response)); } else { free(its_data); DLT_IVI_VLAN04_LOG(DLT_LOG_WARN,DLT_STRING("unknown service id.")); return; } }
时间: 2024-03-12 18:49:49 浏览: 121
可以将多个if语句合并成一个switch语句,这样代码更简洁易读。同时,可以使用unordered_map代替多个map,将不同的服务ID对应的响应消息指针保存在同一个unordered_map中,这样可以避免代码重复。修改后的代码如下:
```
if (vsomeip::message_type_e::MT_REQUEST == _message->get_message_type()) {
std::shared_ptr<vsomeip::message> its_response = vsomeip::runtime::get()->create_response(_message);
uint16_t service_id = _message->get_service();
uint16_t method_id = _message->get_method();
switch (service_id) {
case TBOX_SERVICE_ID_LOCATION:
_location_service_response_map[method_id] = its_response;
break;
case TBOX_SERVICE_ID_TBS:
_tbox_service_response_map[method_id] = its_response;
break;
case TBOX_SERVICE_ID_RESV_UPDATE:
_resvUpdate_service_response_map[method_id] = its_response;
break;
case TBOX_SERVICE_ID_XCALL_VLAN04:
_response_map[method_id] = its_response;
break;
default:
free(its_data);
DLT_IVI_VLAN04_LOG(DLT_LOG_WARN, DLT_STRING("unknown service id."));
return;
}
}
```
阅读全文