以下是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