0
点赞
收藏
分享

微信扫一扫

【ARA com API】ara::core::Optional

哈哈镜6567 2022-01-18 阅读 81
autosarc++

文章目录

ara::core::Optional 是什么

实际上就是std::optional。但是当前的AP标准没有支持到那么新版本的C++标准(我没有具体研究是C++14 还是 17引入的,反正C++11是没有)

AP要求供应商来实现类似功能,放在ARA里叫做ara::core::Optional。

这个类型是实际作用就是可以方便的判断这个值是否存在。对 你没有看错,是否存在。

背后代码的实现方式有些类似与联合(union)。把一个bool 和 你要使用的数据类型联合。如果不存在直接读bool值就是false。

在代码中可以判断这个bool来实现兼容。

标准中的代码示例

类型定义

定义了current 和 health作为可选成员

 /** 
 * \brief Data structure with optional contained values. 
 */ 
 struct BatteryState {
 Voltage_t voltage;
 Temperature_t temperature;
 ara::core::Optional<Current_t> current;
 ara::core::Optional<Health> health;
 };

服务定义

本服务的版本只关心current

 using namespace ara::com;

 class BatteryStateImpl : public BatteryStateSkeleton {
 public: 
 Future<BatteryState> GetBatteryState() {
 // no asynchronous call for simplicity
 ara::core::Promise<BatteryState> promise;

 // fill the data structure
 BatteryState state;
 state.voltage = 14;
 state.temperature = 35;
 state.current = 0;
 // state.health is not set and therefore it is not transmitted

 promise.set_value(state);
 auto future = promise.get_future();
 return future;
 }
 }

客户端

客户端不知道服务里面支持什么可选数据

使用bool操作或者has_value()方法来先判断值是否存在再进行处理。

 using namespace ara::com;

 int main() {
 // some code to acquire handle
 // ...
 BatteryStateProxy bms_service(handle);
 Future<BatteryState> stateFuture = bms_service.GetBatteryState();
 // Receive BatteryState
 BatteryState state = stateFuture.get();

 // Check the optional contained elements for presence
 if(state.current) {
 //Access the value of the optional element with the optional::operator*
 if(*state.current >= MAX_CURRENT) {
 // do something with this information
 }
 }

 // Check with optional::has_value() method
 if(state.health.has_value()){
 // Access the value of the optional element with the optional::value() method
 if(state.health.value() >= BAD_HEALTH) {
 // do something with this information
 }
 }
 }
举报

相关推荐

0 条评论