Changeset 1057


Ignore:
Timestamp:
Feb 7, 2008, 10:37:14 PM (16 years ago)
Author:
Peter
Message:

extended convert function to accept nan and int (and -int if type is signed)

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/yat/utility/utility.h

    r1005 r1057  
    5151   */
    5252  template<typename T>
    53   T convert(const std::string& s)
    54   {
    55     std::stringstream ss(s);
    56     T a;
    57     ss >> a;
    58     bool ok = true;
    59     if(ss.fail())
    60       ok = false;
    61     // Check that nothing is left on stream
    62     std::string b;
    63     ss >> b;
    64     if (!b.empty() || !ok)
    65       throw std::runtime_error(std::string("convert(\"")+s+std::string("\")"));
    66     return a;
    67   }
     53  T convert(const std::string& s);
    6854
    6955  ///
     
    9480  bool is_nan(const std::string& s);
    9581
     82
     83  // template implementations
     84  template<typename T>
     85  T convert(const std::string& s)
     86  {
     87    if (is_nan(s))
     88      return std::numeric_limits<T>::quiet_NaN();
     89    if (is_equal(s, "inf"))
     90      return std::numeric_limits<T>::infinity();
     91    if (is_equal(s, "-inf"))
     92      if (std::numeric_limits<T>::is_signed())
     93        return -std::numeric_limits<T>::infinity();
     94      else
     95        throw std::runtime_error(std::string("convert(\"")+s+
     96                                 std::string("\"): type is unsigned") );
     97    std::stringstream ss(s);
     98    T a;
     99    ss >> a;
     100    bool ok = true;
     101    if(ss.fail())
     102      ok = false;
     103    // Check that nothing is left on stream
     104    std::string b;
     105    ss >> b;
     106    if (!b.empty() || !ok)
     107      throw std::runtime_error(std::string("convert(\"")+s+std::string("\")"));
     108    return a;
     109  }
     110
    96111}}} // of namespace utility, yat, and theplu
    97112
Note: See TracChangeset for help on using the changeset viewer.