开发者

Is this casting safe?

开发者 https://www.devze.com 2023-01-01 22:12 出处:网络
I need to write a Uti开发者_JAVA技巧l function (in my c++cli app) that converts a String to a Double or Float or Int.

I need to write a Uti开发者_JAVA技巧l 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

   template <typename T> 
   T GetValue (const std::string& value) const
   {
      T t;


      try
      {
         t = boost::lexical_cast<T>(value);
      } 
      catch (const boost::bad_lexical_cast&) {
         // It's horrible!
         // (...)
      }

      return t;
   }

Note that this conversion is efficient, because only the appropriate conversion is done. In your case, converting to int would mean invoking conversion to double (which could, and I suspect is less-efficient than plain conversion to int) and evil rounding by your static_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 ToYyy routine and returning the result of the according type.

0

精彩评论

暂无评论...
验证码 换一张
取 消