Convert - DryPerspective/C_Builder_Extras GitHub Wiki
Within C++Builder, type conversion is a little clunky. Embarcadero recommend use of Pascal-style AtoB-style functions, so IntToStr() to convert from an integer type to a string type. This may sound feasible on paper, but in practice it can be awkward to use for multiple reasons.
Firstly it is unusable in generic code
template<typename T>
void get_data(T in){
UnicodeString input_data_as_string = /*What function do we use here?*/
//...
}Similarly, within code where all types are concrete, the conversion functions do not lend themselves well to uses more complex than a single expression, for example
auto money_amount = StrToFloat("4.50");
add_tax_to(money_amount);
Currency curr(money_amount); //This call is ambiguous and will fail compilation without further casts.As such, I provide a simple template function convert_to<T>. By virtue of being a template, this function can deduce the type from which the conversion is desired, meaning no awkward mismatches (e.g. IntToStr vs UIntToStr in the Embarcadero library); and the user can specify exactly which type they wish to receive from the conversion rather than relying on the predetermined type as returned by a named Embarcadero function.
This function supports conversion between the builtin arithmetic types, std::string and std::wstring, and Embarcadero AnsiString, UnicodeString, and Currency types. This as an additional use in C++Builder as it typically does not enjoy support for conversion between VCL types and standard library types. When included on a non-Borland compiler, the C++Builder types are removed from the header and the header can work as an effective solution for converting between builtin types and std::string types. If an invalid type conversion is requested by the user, the code will not compile; though it is unavoidable that it cannot be known until runtime whether a conversion from a string to an arithmetic type will be valid.
| convert_to | A function template to enable easy conversion between types. |
template<typename T>
void get_data(T in){
UnicodeString in_as_string = convert_to<UnicodeString>(in);
//...
}
int main(){
UnicodeString initial_data = get_from_database();
auto money_amount = convert_to<double>(initial_data);
add_tax_to(money_amount);
Currency curr(money_amount); //No longer ambiguous as we control the types ourselves.
}