Mit diesen user defined literals passiert alles zur Compiletime, es braucht nicht mehr Zyklen und mehr Speicher auf dem Target, kann damit auf auf embedded Systemen genutzt werden.
Das geht sicher nicht mit plain C
Code: Alles auswählen
template<int M, int K, int S>
struct Unit { // a unit in the MKS system
enum {m=M, kg=K, s=S };
};
template <typename Unit> // a magnitude with a unit
struct Value {
double val; // the magnitude
constexpr Value(double d) : val(d) {}
};
// Time
using sec = Unit<0,0,1>; // the base unit
using min = Unit<0,0,60>; // minitues
using hour = Unit<0,0,3600>; // hour
using time = Value<sec>; // time: base unit seconds
constexpr time operator"" s(long double d)
{
return time(d);
}
constexpr time operator"" min(long double d)
{
return time(d * min::s);
}
constexpr time operator"" h(long double d)
{
return time(d * hour::s);
}
// Time square
using sec2 = Unit<0,0,2>; // base unit
using time2 = Value<sec2>; // the physical value
constexpr time2 operator"" s2(long double d)
{
return time2(d);
}
// distance
using m = Unit<1,0,0>; // base unit
using km = Unit<1000,0,0>; // kilometers
using distance = Value<m>; // the physical value
constexpr distance operator"" m(long double d)
{
return distance(d);
}
constexpr distance operator"" km(long double d)
{
return distance(d * km::m);
}
// acceleration
using m_s2 = Unit<1,0,-2>; // base unit meters/second/second
using accel = Value<m_s2>; // the physical value
constexpr accel operator"" m_s2 (long double d)
{
return accel(d);
}
// speed
using m_s = Unit<1,0,1>; // the base unit
using speed = Value<m_s>; // the physical value
using km_h = Unit<1000,0,3600>; // km/h
constexpr speed operator"" m_s(long double d)
{
return speed(d);
}
constexpr speed operator/(distance d, time t)
{
return speed(d.val/t.val);
}
int main(int argc, char** argv)
{
time t = 1.0s;
speed s1 = 100.0m / 9.8s; // very fast for a human
speed s2 = 1.2km / 0.5h; // slow going
speed s3 = 1.2km / 30.0min; // the same speed
// speed s2 = 100 / 9.8s; // error
}
[1] http://www.youtube.com/watch?v=0iWb_qi2-uI