Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/objecthierarchy2/src/util/Convert.h @ 2617

Last change on this file since 2617 was 2361, checked in by landauf, 16 years ago
  • Fixed a problem with SUPER in combination with a pure-virtual base-function when called from a direct child of the base-class.
  • Added random number generator initialization to Core (configurable)
  • Fixed a bug in Convert.h
  • Property svn:eol-style set to native
File size: 15.0 KB
RevLine 
[1052]1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
[1505]3 *                    > www.orxonox.net <
[1052]4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
[2087]23 *      Reto Grieder
[1791]24 *      Fabian 'x3n' Landau
[1052]25 *      Benjamin Grauer
[1505]26 *   Co-authors:
[1052]27 *      ...
28 */
29
30/*!
[2087]31    @file
[1052]32    @brief Definition and Implementation of the Convert class.
33*/
34
[2087]35#ifndef _Converter_H__
36#define _Converter_H__
[1052]37
[1062]38#include "UtilPrereqs.h"
39
[1052]40#include <string>
41#include <sstream>
[2087]42#include <istream>
43#include <ostream>
[1837]44#include <typeinfo>
[1052]45
[1747]46#include "Debug.h"
[1625]47#include "String.h"
[1064]48
[2087]49// GCC generates warnings when implicitely casting from float to int for instance.
50// This is however exactly what convertValue does, so we need to suppress these warnings.
51// They only occur when using the ImplicitConversion template.
52#if ORXONOX_COMPILER == ORXONOX_COMPILER_GNUC
53#  pragma GCC system_header
[1064]54#endif
[1052]55
[1505]56
[2087]57///////////////////////////////////////////////
58// Static detection for conversion functions //
59///////////////////////////////////////////////
[1505]60
[2087]61/* The idea to use the sizeof() operator on return functions to determine function existance
62   is described in 'Modern C++ design' by Alexandrescu (2001). */
[1505]63
[2087]64// disable warnings about possible loss of data
65#if ORXONOX_COMPILER == ORXONOX_COMPILER_MSVC
66#  pragma warning(push)
67#  pragma warning(disable:4244)
68#endif
[1505]69
[2171]70namespace orxonox
[1505]71{
[2171]72    template <class FromType, class ToType>
73    class ImplicitConversion
74    {
75    private:
76        ImplicitConversion(); ImplicitConversion(const ImplicitConversion&); ~ImplicitConversion();
77        // Gets chosen only if there is an implicit conversion from FromType to ToType.
78        static char test(ToType);
79        // Accepts any argument. Why do we not use a template? The reason is that with templates,
80        // the function above is only taken iff it is an exact type match. But since we want to
81        // check for implicit conversion, we have to use the ellipsis.
82        static long long test(...);
83        static FromType object; // helper object to handle private c'tor and d'tor
84    public:
85        // test(object) only has 'long long' return type iff the compiler doesn't choose test(...)
86        enum { exists = (sizeof(test(object)) == sizeof(char)) };
87    };
88}
[1505]89
[2087]90#if ORXONOX_COMPILER == ORXONOX_COMPILER_MSVC
91#  pragma warning(pop)
92#endif
[1505]93
94
[2087]95////////////////////////////////////
96//// ACTUAL CONVERSION SEQUENCE ////
97////////////////////////////////////
98/*
99    There is a distinct priority when choosing the right conversion function:
100    Overwrite:
101    1. (Partial) template specialisation of ConverterExplicit::convert()
102    Fallbacks:
103    2. Any possible implicit conversion. This includes 'FooBar' --> 'int' if FooBar defines operator float().
104    3. Global or member operators for stringstream when converting from or to std::string (or FROM const char*)
105    4. (Partial) template specialisation of ConverterFallback::convert()
106    5. Function that simply displays "Could not convert value" with type information obtained from typeid().
[1505]107
[2087]108    Notes:
109    There has to be an exact type match when using template specialisations.
110    Template specialisations can be defined after including this file. Any implicit cast function or iostream
111    operator has to be declared BEFORE this file gets parsed.
[1505]112
[2087]113    Defining your own functions:
114    There are obviously 4 ways to specifiy a user defined conversion. What should I use?
[1505]115
[2087]116    Usually, ConverterFallback fits quite well. You won't have to deal with the conversion from
117    'MyClass' to 'MyClass' by using another explicit template specialisation to avoid ambiguities.
[1505]118
[2087]119    However if you want to overwrite an implicit conversion or an iostream operator, you really need to
120    make use of ConverterExplicit.
121*/
122
[2171]123namespace orxonox
[1505]124{
[2171]125    namespace
126    {
127        //! Little template that maps integers to entire types (Alexandrescu 2001)
128        template <int I>
129        struct Int2Type { };
130    }
[1505]131
132
[2171]133    ///////////////////
134    // No Conversion //
135    ///////////////////
[1505]136
[2171]137    // Default template. No conversion available at all.
138    template <class FromType, class ToType>
139    struct ConverterFallback
[1505]140    {
[2171]141        static bool convert(ToType* output, const FromType& input)
142        {
143            COUT(2) << "Could not convert value of type " << typeid(FromType).name()
144                    << " to type " << typeid(ToType).name() << std::endl;
145            return false;
146        }
147    };
[2087]148
[2171]149    // If all else fails, try a dynamic_cast for pointer types.
150    template <class FromType, class ToType>
151    struct ConverterFallback<FromType*, ToType*>
[1505]152    {
[2171]153        static bool convert(ToType** output, FromType* const input)
[2087]154        {
[2171]155            ToType* temp = dynamic_cast<ToType*>(input);
156            if (temp)
157            {
158                *output = temp;
159                return true;
160            }
161            else
162                return false;
[2087]163        }
[2171]164    };
165}
[1505]166
167
[2087]168///////////////////////
169// ConverterFallback //
170///////////////////////
171
172// Default template for stringstream
173template <class FromType, class ToType>
174struct ConverterStringStream
[1505]175{
176    static bool convert(ToType* output, const FromType& input)
177    {
[2171]178        return orxonox::ConverterFallback<FromType, ToType>::convert(output, input);
[1505]179    }
180};
181
182
183/////////////
[2087]184// OStream //
[1505]185/////////////
186
[2087]187namespace fallbackTemplates
[1505]188{
[2087]189    template <class FromType>
190    inline bool operator <<(std::ostream& outstream,  const FromType& input)
191    {
192        std::string temp;
[2171]193        if (orxonox::ConverterFallback<FromType, std::string>::convert(&temp, input))
[2087]194        {
195            std::operator <<(outstream, temp);
196            return true;
197        }
198        else
199            return false;
200    }
201}
[1505]202
[2087]203// template that evaluates whether we can convert to std::string via ostringstream
[1505]204template <class FromType>
[2087]205struct ConverterStringStream<FromType, std::string>
[1505]206{
207    static bool convert(std::string* output, const FromType& input)
208    {
[2087]209        using namespace fallbackTemplates;
210        // this operator call only chooses fallbackTemplates::operator<< if there's no other fitting function
[1505]211        std::ostringstream oss;
212        if (oss << input)
213        {
214            (*output) = oss.str();
215            return true;
216        }
217        else
218            return false;
219    }
220};
221
[2087]222
223/////////////
224// IStream //
225/////////////
226
227namespace fallbackTemplates
[1625]228{
[2087]229    template <class ToType>
230    inline bool operator >>(std::istream& instream, ToType& output)
231    {
[2171]232        return orxonox::ConverterFallback<std::string, ToType>
[2087]233            ::convert(&output, static_cast<std::istringstream&>(instream).str());
234    }
[1625]235}
236
[2087]237// template that evaluates whether we can convert from std::string via ostringstream
[1505]238template <class ToType>
[2087]239struct ConverterStringStream<std::string, ToType>
[1505]240{
241    static bool convert(ToType* output, const std::string& input)
242    {
[2087]243        using namespace fallbackTemplates;
[1505]244        std::istringstream iss(input);
[2087]245        // this operator call only chooses fallbackTemplates::operator>> if there's no other fitting function
[1505]246        if (iss >> (*output))
[2087]247        {
[1505]248            return true;
[2087]249        }
[1505]250        else
251            return false;
252    }
253};
254
[2171]255namespace orxonox
[1625]256{
[1505]257
[2171]258    ///////////////////
259    // Implicit Cast //
260    ///////////////////
[1625]261
[2171]262    // implicit cast not possible, try stringstream conversion next
263    template <class FromType, class ToType>
264    inline bool convertImplicitely(ToType* output, const FromType& input, orxonox::Int2Type<false>)
[1505]265    {
[2171]266        return ConverterStringStream<FromType, ToType>::convert(output, input);
[1505]267    }
268
[2171]269    // We can cast implicitely
270    template <class FromType, class ToType>
271    inline bool convertImplicitely(ToType* output, const FromType& input, orxonox::Int2Type<true>)
272    {
273        (*output) = static_cast<ToType>(input);
[2087]274        return true;
[1505]275    }
276
277
[2171]278    ////////////////////////////////
279    // ConverterExplicit Fallback //
280    ////////////////////////////////
[1505]281
[2171]282    // Default template if no specialisation is available
283    template <class FromType, class ToType>
284    struct ConverterExplicit
285    {
286        static bool convert(ToType* output, const FromType& input)
287        {
288            // Try implict cast and probe first. If a simple cast is not possible, it will not compile
289            // We therefore have to out source it into another template function
290            const bool probe = ImplicitConversion<FromType, ToType>::exists;
291            return convertImplicitely(output, input, orxonox::Int2Type<probe>());
292        }
293    };
[2087]294
295
[2171]296    //////////////////////
297    // Public Functions //
298    //////////////////////
[2087]299
[2171]300    /**
301    @brief
302        Converts any value to any other as long as there exists a conversion.
303        Otherwise, the conversion will generate a runtime warning and return false.
304        For information about the different conversion methods (user defined too), see the section
305        'Actual conversion sequence' in this file above.
306    */
307    template <class FromType, class ToType>
308    inline bool convertValue(ToType* output, const FromType& input)
309    {
310        return ConverterExplicit<FromType, ToType>::convert(output, input);
311    }
[2087]312
[2171]313    // For compatibility reasons. The same, but with capital ConvertValue
314    template<class FromType, class ToType>
315    inline bool ConvertValue(ToType* output, const FromType& input)
316    {
317        return convertValue(output, input);
318    }
[2087]319
[2171]320    // Calls convertValue and returns true if the conversion was successful.
321    // Otherwise the fallback is used.
322    /**
323    @brief
324        Converts any value to any other as long as there exists a conversion.
325        Otherwise, the conversion will generate a runtime warning and return false.
326        For information about the different conversion methods (user defined too), see the section
327        'Actual conversion sequence' in this file above.
328        If the conversion doesn't succeed, 'fallback' is written to '*output'.
329    @param fallback
330        A default value that gets written to '*output' if there is no conversion.
331    */
332    template<class FromType, class ToType>
333    inline bool convertValue(ToType* output, const FromType& input, const ToType& fallback)
[1625]334    {
[2171]335        if (convertValue(output, input))
336            return true;
337        else
338        {
339            (*output) = fallback;
340            return false;
341        }
[1625]342    }
343
[2171]344    // for compatibility reason. (capital 'c' in ConvertValue)
345    template<class FromType, class ToType>
346    inline bool ConvertValue(ToType* output, const FromType& input, const ToType& fallback)
[1505]347    {
[2171]348        return convertValue(output, input, fallback);
[1505]349    }
[2171]350
351    // Directly returns the converted value, even if the conversion was not successful.
352    template<class FromType, class ToType>
353    inline ToType getConvertedValue(const FromType& input)
[1505]354    {
[2171]355        ToType output;
356        convertValue(&output, input);
357        return output;
[1505]358    }
[2171]359
360    // Directly returns the converted value, but uses the fallback on failure.
361    template<class FromType, class ToType>
362    inline ToType getConvertedValue(const FromType& input, const ToType& fallback)
[1505]363    {
[2171]364        ToType output;
365        convertValue(&output, input, fallback);
366        return output;
[1505]367    }
[2171]368
369    // Like getConvertedValue, but the template argument order is in reverse.
370    // That means you can call it exactly like static_cast<ToType>(fromTypeValue).
371    template<class ToType, class FromType>
372    inline ToType omni_cast(const FromType& input)
[1505]373    {
[2171]374        ToType output;
375        convertValue(&output, input);
376        return output;
[1505]377    }
378
[2171]379    // convert to string Shortcut
380    template <class FromType>
381    inline std::string convertToString(FromType value)
382    {
383      return getConvertedValue<FromType, std::string>(value);
384    }
[2087]385
[2171]386    // convert from string Shortcut
387    template <class ToType>
388    inline ToType convertFromString(std::string str)
[1505]389    {
[2171]390      return getConvertedValue<std::string, ToType>(str);
[1505]391    }
392
[2171]393    ////////////////////////////////
394    // Special string conversions //
395    ////////////////////////////////
396
397    // Delegate conversion from const char* to std::string
398    template <class ToType>
399    struct ConverterExplicit<const char*, ToType>
[1625]400    {
[2171]401        static bool convert(ToType* output, const char* input)
[1625]402        {
[2171]403            return convertValue<std::string, ToType>(output, input);
[1625]404        }
[2171]405    };
406
407    // These conversions would exhibit ambiguous << or >> operators when using stringstream
408    template <>
409    struct ConverterExplicit<char, std::string>
410    {
411        static bool convert(std::string* output, const char input)
[1625]412        {
[2171]413            *output = std::string(1, input);
414            return true;
[1625]415        }
[2171]416    };
417    template <>
418    struct ConverterExplicit<unsigned char, std::string>
419    {
420        static bool convert(std::string* output, const unsigned char input)
421        {
422            *output = std::string(1, input);
423            return true;
424        }
425    };
426    template <>
427    struct ConverterExplicit<std::string, char>
428    {
429        static bool convert(char* output, const std::string input)
430        {
431            if (input != "")
432                *output = input[0];
433            else
434                *output = '\0';
435            return true;
436        }
437    };
438    template <>
439    struct ConverterExplicit<std::string, unsigned char>
440    {
441        static bool convert(unsigned char* output, const std::string input)
442        {
443            if (input != "")
444                *output = input[0];
445            else
446                *output = '\0';
447            return true;
448        }
449    };
[1625]450
[2171]451
452    // bool to std::string
453    template <>
454    struct ConverterExplicit<bool, std::string>
455    {
456        static bool convert(std::string* output, const bool& input)
457        {
458            if (input)
459              *output = "true";
460            else
461              *output = "false";
[2361]462            return true;
[2171]463        }
464    };
[1625]465
[2171]466    // std::string to bool
467    template <>
468    struct ConverterExplicit<std::string, bool>
469    {
470        static bool convert(bool* output, const std::string& input)
471        {
472            std::string stripped = getLowercase(removeTrailingWhitespaces(input));
473            if (stripped == "true" || stripped == "on" || stripped == "yes")
474            {
475              *output = true;
476              return true;
477            }
478            else if (stripped == "false" || stripped == "off" || stripped == "no")
479            {
480              *output = false;
481              return true;
482            }
483
484            std::istringstream iss(input);
485            if (iss >> (*output))
486                return true;
487            else
488                return false;
489        }
490    };
491}
492
[1052]493#endif /* _Convert_H__ */
Note: See TracBrowser for help on using the repository browser.