The method makes extensive use of C++ templates to track the dimensions of quantities at compile-time. The basic idea is straight-forward and is illustrated by three simple C++ program fragments. The first fragment declares a class Dim which represents dimensioned quantities in a dimensional space characterized by the three dimensions mass, length and time.
template<int M, int L, int T> class Dim {
double val; //Actual value.
public:
Dim(double v= 0) { val= v; } //Constructor.
double value() { return val; }//Accessor.
};
When the Dim class is used for a particular dimension, the
template arguments M, L and T provided should
correspond to the exponents of mass, length and time in that
dimension. Using this class it is easy to enforce dimensional
consistency. For example, to enforce the restriction that only
quantities having identical dimensions can be added together, we
can overload the + operator to work on Dims as
follows:
template<int M, int L, int T>
Dim<M, L, T> operator+(Dim<M, L, T> &d1,
Dim<M, L, T> &d2) {
return Dim<M, L, T>(d1.value() + d2.value());
}
Since operator+ is defined only for Dims with the same
template arguments (corresponding to the same dimensional exponents),
the C++ compiler will enforce the restriction that only
quantities having identical dimensions can be added together.
Multiplying two dimensioned quantities together produces a dimensioned quantity whose dimensional exponents are the sum of the dimensional exponents of the operands. Again, using template arguments for the dimensional exponents, we can overload the * operator to work on Dims as follows:
template<int M1, int L1, int T1,
int M2, int L2, int T2>
Dim<M1 + M2, L1 + L2, T1 + T2>
operator*(Dim<M1, L1, T1> &d1,
Dim<M2, L2, T2> &d2) {
return Dim<M1 + M2, L1 + L2, T1 + T2>
(d1.value() * d2.value());
}
The above examples summarize the essential ideas behind the proposed method. The rest is mere syntactic sugar (though essential to developing a usable system).