//=========
//units.hpp
//=========
#ifndef UNITS_HPP_INCLUDED
#define UNITS_HPP_INCLUDED
namespace units
{
template <int L, int T, int M>
struct Unit
{
double value;
double coeff;
Unit<L, T, M> (double value)
{
this->value = value;
this->coeff = 1;
}
Unit<L, T, M> (double value, double coeff)
{
this->value = value;
this->coeff = coeff;
}
Unit<L, T, M> (double value, const Unit<L, T, M> & unit) {
this->value = value;
this->coeff = unit.coeff;
}
Unit<L, T, M> (const Unit<L, T, M> & quantity) {
this->value = quantity.value;
this->coeff = quantity.coeff;
}
Unit<L, T, M> & convert(const Unit<L, T, M> & unit) {
value = value * coeff / unit.coeff;
coeff = unit.coeff;
return (*this);
}
Unit<L, T, M> & operator= (const Unit<L, T, M> & other) {
this->value = other.value;
this->coeff = other.coeff;
return (*this);
}
};
template <int L, int T, int M>
Unit<L, T, M> operator+ (const Unit<L, T, M> & a, const Unit<L, T, M> & b)
{
Unit<L, T, M> result(a);
result.value += b.value*b.coeff/a.coeff;
return result;
}
template <int L, int T, int M>
Unit<L, T, M> operator- (const Unit<L, T, M> & a, const Unit<L, T, M> & b)
{
Unit<L, T, M> result(a);
result.value -= b.value*b.coeff/a.coeff;
return result;
}
template <int La, int Ta, int Ma, int Lb, int Tb, int Mb>
Unit<La + Lb, Ta + Tb, Ma + Mb> operator* (const Unit<La, Ta, Ma> & a, const Unit<Lb, Tb, Mb> & b)
{
Unit<La + Lb, Ta + Tb, Ma + Mb> result(a.value * b.value);
result.coeff = a.coeff * b.coeff;
return result;
}
template <int La, int Ta, int Ma, int Lb, int Tb, int Mb>
Unit<La - Lb, Ta - Tb, Ma - Mb> operator/ (const Unit<La, Ta, Ma> & a, const Unit<Lb, Tb, Mb> & b)
{
Unit<La - Lb, Ta - Tb, Ma - Mb> result(a.value / b.value);
result.coeff = a.coeff / b.coeff;
return result;
}
typedef Unit<1, 0, 0> Length;
typedef Unit<0, 1, 0> Time;
typedef Unit<1, -1, 0> Speed;
static const Length meter(1.0);
static const Time second(1.0);
static const Length kilometer(1.0, 1000.0);
static const Time hour(1.0, 3600.0);
}
#endif
//========
//main.cpp
//========
#include "units.hpp"
#include <iostream>
using std::cout;
using std::endl;
using namespace units;
int main()
{
Length l(10.0, meter);
Time t(3.0, second);
Speed v = l / t;
v.convert(kilometer/hour);
cout << v.value << endl;
}