2.6.5 User Defined Literals

Have you ever mixed some units like in the declartion of m below?

struct mass 
{ 
  mass(float kg) 
    : kilograms(kg) 
  {} 
 
  float kilograms; 
}; 
 
void foo() 
{ 
  // A mass of 2000 grams. 
  mass m(2000); 
 
  // Oops, mass() takes the value in kilograms :( 
}

If you have already made this mistake, or just if you use this kind of code, you may be happy to learn that you can now use custom suffixes for literals, which may help to explicit the unit.

// We define the ā€™gā€™ suffix for float numbers, to represent grams. 
mass operator""
_g(float v) 
{ 
  return mass(v / 1000); 
} 
 
void foo() 
{ 
  // A mass of 2000 grams. 
  mass m = 2000_g; 
 
  // m.kilograms is equal to 2, everything is fine. 
}