I need to write a Util function (in my c++cli app) that converts a String to a Double or Float or Int.
template<typename T>
static T MyConvert(String^ str) {
return static_cast<T>(System::Convert::ToDouble(str));
}
Is this safe?
Can it somehow convert 2 to 1.999 and then to 1 if I call MyConvert<int>("2") ?
I was wondering why the Convert class isn’t templated in the first place? (That would let me call Convert<T> instead of Convert.ToDouble() for all types)
This is C++/Cli so I can use any convert methods in c++ or .net, but I only know Convert.ToDouble()|ToString()|ToInt32())
The way this is written in non-CLI environment would mean something like
Note that this conversion is efficient, because only the appropriate conversion is done. In your case, converting to
intwould mean invoking conversion to double (which could, and I suspect is less-efficient than plain conversion to int) and evil rounding by yourstatic_cast.Why even tend to do that?
Try the same approach as I used in my sample, but ported to CLI. Specialize your templates for
MyConvert<int>,MyConvert<double>calls or even make two separate methods (because writing template function with only two suitable template parameters isn’t the best way to design your application).Each of these methods / template specializations would mean calling the appropriate
ToYyyroutine and returning the result of the according type.