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

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
 }
 }
 }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小羊苏C

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值