分析模式-计量的C++实现——完美版本

本文提供了一个计量模板类的改进版本,用于处理带有单位的数值,支持单位转换和不同单位之间的运算。内容包括计量类的设计、权重和长度单位的示例,以及相关的测试代码,确保类的正确性和灵活性。
摘要由CSDN通过智能技术生成

以下是http://www.csdn.net/develop/Article/14/14487.shtm的一个改进版本,本来是作为评论附在上一篇文章后面的,但是作为评论发表的话,会丢失很多文字,很奇怪的说。本文是我和singleracer讨论的结果,个人认为几乎接近完美,希望能对大家有帮助,大家可以自己加入其它的单位体系和单位。

计量的模板类:

#ifndef _QUANTITY_H_
#define _QUANTITY_H_

#ifdef _DEBUG
#define ASSERT_SAME_TYPE( T1, T2) do {T1 v=T2();v; }while(false)
#else
#define ASSERT_SAME_TYPE( T1, T2)
#endif

#include "singleton.h"

template<class UnitType>
struct UnitTraits {
 typedef UnitType::Validator Validator;
};

template<class ValueType>
class ValueTraits {
public:
 static bool equal(const ValueType & l, const ValueType & r)
 {return (l == r);}
};

template<>
class ValueTraits<double> {
public:
 static bool equal(const double & l, const double & r)
 {
  static double precision = 0.000000001;
  return (l - r < precision);
 }
};

template<>
class ValueTraits<float> {
public:
 static bool equal(const float & l, const float & r)
 {
  static float precision = 0.000000001f;
  return (l - r < precision);
 }
};

template<typename ValueType, class UnitValidator, class _Traits = ValueTraits<ValueType> >
class Quantity
{
public:
 typedef UnitValidator Validator;

 template<typename UnitType>Quantity(const ValueType & amount, const UnitType & )
  : m_amount(amount), m_unit(Singleton< unit_wrap<UnitType, ValueType> >::Instance())
 {
  ASSERT_SAME_TYPE(UnitTraits<UnitType>::Validator, Validator);
 }
 ~Quantity()
 {
 }
 Quantity(const Quantity & other)
  : m_amount(o

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值