util.cpp

Go to the documentation of this file.
00001 /* $Id: util.cpp 26756 2008-05-21 18:25:25Z mordante $ */
00002 /*
00003    Copyright (C) 2005 - 2008 by Philippe Plantier <ayin@anathas.org>
00004    Part of the Battle for Wesnoth Project http://www.wesnoth.org/
00005 
00006    This program is free software; you can redistribute it and/or modify
00007    it under the terms of the GNU General Public License version 2
00008    or at your option any later version.
00009    This program is distributed in the hope that it will be useful,
00010    but WITHOUT ANY WARRANTY.
00011 
00012    See the COPYING file for more details.
00013 */
00014 
00015 /**
00016  *  @file util.cpp
00017  *  String-routines - Templates for lexical_cast & lexical_cast_default.
00018  */
00019 
00020 #include "util.hpp"
00021 #include <cstdlib>
00022 
00023 template<>
00024 int lexical_cast<int, const std::string&>(const std::string& a)
00025 {
00026     char* endptr;
00027     int res = strtol(a.c_str(), &endptr, 10);
00028 
00029     if (a.empty() || *endptr != '\0') {
00030         throw bad_lexical_cast();
00031     } else {
00032         return res;
00033     }
00034 }
00035 
00036 template<>
00037 int lexical_cast<int, const char*>(const char* a)
00038 {
00039     char* endptr;
00040     int res = strtol(a, &endptr, 10);
00041 
00042     if (*a == '\0' || *endptr != '\0') {
00043         throw bad_lexical_cast();
00044     } else {
00045         return res;
00046     }
00047 }
00048 
00049 template<>
00050 int lexical_cast_default<int, const std::string&>(const std::string& a, int def)
00051 {
00052     if(a.empty()) {
00053         return def;
00054     }
00055 
00056     char* endptr;
00057     int res = strtol(a.c_str(), &endptr, 10);
00058 
00059     if (*endptr != '\0') {
00060         return def;
00061     } else {
00062         return res;
00063     }
00064 }
00065 
00066 template<>
00067 int lexical_cast_default<int, const char*>(const char* a, int def)
00068 {
00069     if(*a == '\0') {
00070         return def;
00071     }
00072 
00073     char* endptr;
00074     int res = strtol(a, &endptr, 10);
00075 
00076     if (*endptr != '\0') {
00077         return def;
00078     } else {
00079         return res;
00080     }
00081 }
00082 
00083 template<>
00084 double lexical_cast_default<double, const std::string&>(const std::string& a, double def)
00085 {
00086     if(a.empty()) {
00087         return def;
00088     }
00089 
00090     char* endptr;
00091     double res = strtod(a.c_str(), &endptr);
00092 
00093     if (*endptr != '\0') {
00094         return def;
00095     } else {
00096         return res;
00097     }
00098 }
00099 

Generated by doxygen 1.5.5 on 23 May 2008 for The Battle for Wesnoth
Gna! | Forum | Wiki | CIA | devdocs