views:

101

answers:

1

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())

Thanks

+1  A: 
Kotti
Why can't I use the same exact method? Why do I need to specialize my templates?
Itsik
@Itsik As long as it's not your bottleneck and you don't experience troubles, you *CAN*. But in this terms you also *CAN* write all your code in one line (as long as it works). This answer is just my opinion - how would I implement that and why do I think that would be more effective. Of course, the last decision is up to you.
Kotti
@Kotti Maybe I didn't understand the answer properly. GetValue<T>() looks like a good method to me that gets the job done. I didn't understand the additional part, why I would want to specialize my Template if I went with GetValue. Were you suggesting an alternative option ?
Itsik
@Itsik Oh, of course you can use that `GetValue<T>` if you wish to. I thought the question was to find proper implementation *without `boost` usage* (which could be problematic, because in CLI you don't have universal casting method like `boost::lexical_cast` and, hence you should specialize templated method to acquire the same functionality).
Kotti
@Kotti I'll import boost into my project, about time anyway :)
Itsik