C++ TMP units of measure POC
#include "stdafx.h"
class m { };
class kg { };
class s { };
template<typename T, int pm, int pkg, int ps>
class unit
{
public:
T value;
unit(T value) : value(value)
{
}
};
template<typename T, int pm, int pkg, int ps>
unit<T, pm, pkg, ps> operator+(const unit<T, pm, pkg, ps> &x, const unit<T, pm, pkg, ps> &y)
{
return unit<T, pm, pkg, ps>(x.value + y.value);
}
template<typename T, int pm, int pkg, int ps>
unit<T, pm, pkg, ps> operator-(const unit<T, pm, pkg, ps> &x, const unit<T, pm, pkg, ps> &y)
{
return unit<T, pm, pkg, ps>(x.value - y.value);
}
template<typename T, int pmx, int pkgx, int psx, int pmy, int pkgy, int psy>
unit<T, pmx + pmy, pkgx + pkgy, psx + psy> operator*(const unit<T, pmx, pkgx, psx> &x, const unit<T, pmy, pkgy, psy> &y)
{
return unit<T, pmx + pmy, pkgx + pkgy, psx + psy>(x.value * y.value);
}
template<typename T, int pmx, int pkgx, int psx, int pmy, int pkgy, int psy>
unit<T, pmx - pmy, pkgx - pkgy, psx - psy> operator/(const unit<T, pmx, pkgx, psx> &x, const unit<T, pmy, pkgy, psy> &y)
{
return unit<T, pmx - pmy, pkgx - pkgy, psx - psy>(x.value / y.value);
}
int _tmain()
{
auto foo = unit<float, 1, 0, 0>(5) + unit<float, 1, 0, 0>(10);
printf("%f\n", foo.value);
auto bar = unit<float, 0, 0, 1>(2) * unit<float, 0, 0, 1>(3) + unit<float, 0, 0, 2>(4);
printf("%f\n", bar.value);
}