CppDB
cppdb/numeric_util.h
00001 
00002 //                                                                             
00003 //  Copyright (C) 2010-2011  Artyom Beilis (Tonkikh) <artyomtnk@yahoo.com>     
00004 //                                                                             
00005 //  Distributed under:
00006 //
00007 //                   the Boost Software License, Version 1.0.
00008 //              (See accompanying file LICENSE_1_0.txt or copy at 
00009 //                     http://www.boost.org/LICENSE_1_0.txt)
00010 //
00011 //  or (at your opinion) under:
00012 //
00013 //                               The MIT License
00014 //                 (See accompanying file MIT.txt or a copy at
00015 //              http://www.opensource.org/licenses/mit-license.php)
00016 //
00018 #ifndef CPPDB_NUMERIC_UTIL_H
00019 #define CPPDB_NUMERIC_UTIL_H
00020 
00021 #include <cppdb/errors.h>
00022 #include <string>
00023 #include <sstream>
00024 #include <limits>
00025 #include <iomanip>
00026 
00027 namespace cppdb {
00028 
00035         template<typename T>
00036         T parse_number(std::string const &s,std::istringstream &ss)
00037         {
00038                 ss.clear();
00039                 ss.str(s);
00040                 if(s.find_first_of(".eEdD")!=std::string::npos) {
00041                         long double v;
00042                         ss >> v;
00043                         if(ss.fail() || !std::ws(ss).eof())
00044                                 throw bad_value_cast();
00045 #ifdef __BORLANDC__
00046 #pragma warn -8008 // condition always true/false
00047 #pragma warn -8066 // unreachable code
00048 #endif
00049                         if(std::numeric_limits<T>::is_integer) {
00050                                 if(v > std::numeric_limits<T>::max() || v < std::numeric_limits<T>::min())
00051                                         throw bad_value_cast();
00052                         }
00053 #ifdef __BORLANDC__
00054 #pragma warn .8008
00055 #pragma warn .8066
00056 #endif
00057                         return static_cast<T>(v);
00058                 }
00059                 T v;
00060                 ss >> v;
00061                 if(ss.fail() || !std::ws(ss).eof()) 
00062                         throw bad_value_cast();
00063                 if(     std::numeric_limits<T>::is_integer 
00064                         && !std::numeric_limits<T>::is_signed 
00065                         && s.find('-') != std::string::npos 
00066                         && v!=0) 
00067                 {
00068                         throw bad_value_cast();
00069                 }
00070                 return v;
00071         }
00072 
00073 
00074 }
00075 #endif
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator