Using a conversion function (C++)

From RAD Studio
Jump to: navigation, search

Go Up to Converting measurements (C++)

For cases when the conversion is more complex, you can use a different syntax to specify a function to perform the conversion instead of using a conversion factor. For example, you can't convert temperature values using a conversion factor, because different temperature scales have a different origins.

This example, which is translated from the StdConvs unit, shows how to register a conversion type by providing functions to convert to and from the base units.

Declare variables

First, declare variables for the identifiers. The identifiers are used in the cbTemperature conversion family, and the units of measurement are its members:

TConvFamily cbTemperature;
TConvType tuCelsius;
TConvType tuKelvin;
TConvType tuFahrenheit;

Note: The units of measurement listed here are a subset of the temperature units actually registered in the StdConvs unit.

Register the conversion family

Next, register the conversion family:

cbTemperature = RegisterConversionFamily("Temperature");

Register the base unit

Next, define and register the base unit of the conversion family, which in the example is degrees Celsius. Note that in the case of the base unit, we can use a simple conversion factor, because there is no actual conversion to make:

tuCelsius = RegisterConversionType(cbTemperature, "Celsius", 1);

Write methods to convert to and from the base unit

You need to write the code that performs the conversion from each temperature scale to and from degrees Celsius, because these do not rely on a simple conversion factor. These functions are translated from the StdConvs unit:

double __fastcall FahrenheitToCelsius(const double AValue) {
    return (((AValue - 32) * 5) / 9);
}

double __fastcall CelsiusToFahrenheit(const double AValue) {
    return (((AValue * 9) / 5) + 32);
}

double __fastcall KelvinToCelsius(const double AValue) {
    return (AValue - 273.15);
}

double __fastcall CelsiusToKelvin(const double AValue) {
    return (AValue + 273.15);
}

Register the other units

Now that you have the conversion functions, you can register the other measurement units within the conversion family. You also include a description of the units.

The code to register the other units in the family is shown here:

tuKelvin = RegisterConversionType(cbTemperature, "Kelvin", KelvinToCelsius,
		CelsiusToKelvin);
tuFahrenheit = RegisterConversionType(cbTemperature, "Fahrenheit",
		FahrenheitToCelsius, CelsiusToFahrenheit);

Use the new units

You can now use the newly registered units to perform conversions in your applications. The global Convert function can convert between any of the conversion types that you registered with the cbTemperature conversion family. For example the following code converts a value from degrees Fahrenheit to degrees Kelvin.

Convert(StrToFloat(Edit1->Text), tuFahrenheit, tuKelvin);

See Also