parts/6.02.TypeSystem-IHN.md

6.2 Type System [IHN]

6.2.1 Applicability to language

C++ is a statically typed language. In some ways, C++ is both strongly and weakly typed, as it requires all objects/expressions to have a type, but allows for some implicit conversions of values from one type to another type. The following cases require special consideration:

double fluxcompensation(double flux, bool compensate){
  if (flux) { // double to bool conversion
    double delta = compute_delta();
    double const compensate_v = 1.4;
    return flux + delta * compensate; // bool to double conversion
  } 
  return 1.;
}

Note that type aliases (using, typedef) do not define a different type from their alias just a different name and thus do not incur any conversion between the alias and the aliased type.

Instead of using the built-in arithmetic types or generic library types such as std::string for your domain values, C++ allows to wrap them in user-defined-class types as so-called strong types. For integral values, enum class types can also be used. Strong types provide only those operator overloads and conversions for each such type that make sense in the application domain. User-defined-literal operators help with providing constants of appropriate strong types. Such strong types provide full control of conversions and operations available, avoiding semantically unsound operations that the built-in or other generic types might provide.

For example, a very simple strong type representation of temperature values can be implemented as follows:

struct Celsius {
    double value;
};
struct Fahrenheit {
    double value;
};
Fahrenheit convert_to_fahrenheit(Celsius c){
    return { 9*c.value/5+32};
}
//...
Celsius wrong = convert_to_fahrenheit({20.}); // doesn't compile

In a realistic scenario using a library for strong type support eases the definition and use of strong types.

6.2.2 Avoidance mechanisms for language users

To avoid the vulnerability or mitigate its ill effects, C++ software developers can: - Use the avoidance mechanisms of ISO/IEC TR 24772-1:2019, 6.2.5. and the guidance provided in the different related sections of this document.