Classes in D and C++

Andy Little andy at servocomm.freeserve.co.uk
Mon Mar 5 01:22:17 PST 2007


Lionello Lunesu Wrote:

> SomeType st = 2;//construction
> 
> No need for constructors ;)

OK, To explain why I don't want to allow this syntax I need to explain som of how the quan library works.

Its main purpose is to catch errors in dimensional analysis.

So for example :

assume some types representing Force, Mass and Acceleration.

Now I say

Mass m;
Acceleration;
Force f = m * a; // OK this is dimensionally correct according to Physics.

However If I say:

Force f = m / a; // Error. This is dimensionally not correct and the library is designed to not allow this to compile.

In fact the dimension of all physical quantities can be represented as combinations of powers of the base dimensions  e.g( in The SI system):

length, mass, time, temperature, current, substance, intensity.

Force for example is mass^1, length ^1, time ^-2 etc.
(Just to jog the memory of Physics lessons)
(And behind the scenes this is how the library works, by computing the resulting dimension in a calculation using metaprogramming)

Also there are so called dimensionless quantities and these are represented in the library by inbuilt types.
e.g int, double etc are seen by the library as dimensionless types, and certain calculations Do result in dimensionless types.

E.g:

Length L1, L2;
double ratio  = L1/ L2; // OK the result is dimensionless so is a numeric type.


Therefore I don't allow the syntax:

Length L= 1;

As it is dimensionally incorrect to convert a numeric type to a physical quantity

I do however allow the syntax

Length L(1);

It is specifically allowed to allow value initialisation of a physical_quantity from a numeric. (At some point you need to load the initial value and experience of quan library shows this works and is a compact way to express it)

In C++ these 2 forms of initialisation can be differentiated by  making the constructor explicit, which is basically how I deal with it in C++.

I can get the explicit syntax in D I think by using a static OpCall, but I cant avoid the implicit construction :-(

Finally The physical quantity class is actually more complicated and can be constructed with dimensionally equivalent quantities but with other units and so on. I am not sure how I would tackle that problem in D, but at the moment I am stuck on this one.

regards
Andy Little







More information about the Digitalmars-d mailing list