如何在c ++界面中处理单元 [英] How to handle units in c++ interface

查看:68
本文介绍了如何在c ++界面中处理单元的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在设计一个API,我希望用户能够编写如下代码:

I am currently designing an API where I want that the user to be able to write code like this:

PowerMeter.forceVoltage(1 mV);
PowerMeter.settlingTime(1 ms);

目前我们使用以下定义:

Currently we do this using defines like:

#define mV *1.0e-03

它非常方便用户编写他们的代码,它也非常易读,但是当然也有缺点:

This makes it very convenient for the user to write their code and it is also very readable, but of course has also drawbacks:

int ms;

会引发一些很难理解的编译器错误。所以我正在寻找一个更好的解决方案。

Will throw some compiler errors which are hard to understand. So I am looking for a better solution.

我尝试了新的C ++ 11字面量,但这一切我可以实现是

I tried the new C++11 literals, but with this all I could achieve is:

long double operator "" _mV(long double value) {
  return value * 1e-3;
}
PowerMeter.forceVoltage(1_mV);

最后API不关心像Volt或第二个单位,所以我不想做任何检查,如果你真的输入伏特在forceVoltage或不。所以这也应该是可能的:

In the end the API does not care about the unit like Volt or second but only takes the number, so I don't want to do any checking if you really input Volts in forceVoltage or not. So this should also be possible:

PowerMeter.forceVoltage(2 ms);

除了保留定义之外,还有什么想法吗?

Any idea besides staying with the defines?

推荐答案

我喜欢避免宏在哪里可以,这是一个例子,应该是可能的。
给出正确尺寸的一个轻量级解决方案是:

I prefer avoiding macros where ever I can, and this is an example where it should be possible. One lightweight solution that gives you correct dimensions would be:

static double m = 1;
static double cm = 0.1;
static double mV = 0.001;

double distance = 10*m + 10*cm;

这也反映了物理概念,单位是与值相乘的东西。

This also reflects the physical concept that units are something that's multiplied with the value.

这篇关于如何在c ++界面中处理单元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆