Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/core4/src/util/Convert.h @ 3290

Last change on this file since 3290 was 3265, checked in by rgrieder, 15 years ago
  • Removed superfluous convertToString and convertFromString (replaced them with multi_cast)
  • Replaced all getConvertedValue with multi_cast since it doesn't involve a potential implicit cast of the argument (template type deduction always leads to the right type)
  • Using NilValue<T>() instead of zeroise<T>() for better performance (detail, but just caught my eye)
  • Property svn:eol-style set to native
File size: 14.2 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>
[1837]42#include <typeinfo>
[1052]43
[1747]44#include "Debug.h"
[3250]45#include "StringUtils.h"
[1064]46
[2087]47// GCC generates warnings when implicitely casting from float to int for instance.
48// This is however exactly what convertValue does, so we need to suppress these warnings.
49// They only occur when using the ImplicitConversion template.
[2710]50#ifdef ORXONOX_COMPILER_GCC
[2087]51#  pragma GCC system_header
[1064]52#endif
[1052]53
[1505]54
[2087]55///////////////////////////////////////////////
56// Static detection for conversion functions //
57///////////////////////////////////////////////
[1505]58
[2087]59/* The idea to use the sizeof() operator on return functions to determine function existance
60   is described in 'Modern C++ design' by Alexandrescu (2001). */
[1505]61
[2087]62// disable warnings about possible loss of data
[2710]63#ifdef ORXONOX_COMPILER_MSVC
[2087]64#  pragma warning(push)
65#  pragma warning(disable:4244)
66#endif
[1505]67
[2171]68namespace orxonox
[1505]69{
[2171]70    template <class FromType, class ToType>
71    class ImplicitConversion
72    {
73    private:
74        ImplicitConversion(); ImplicitConversion(const ImplicitConversion&); ~ImplicitConversion();
75        // Gets chosen only if there is an implicit conversion from FromType to ToType.
76        static char test(ToType);
77        // Accepts any argument. Why do we not use a template? The reason is that with templates,
78        // the function above is only taken iff it is an exact type match. But since we want to
79        // check for implicit conversion, we have to use the ellipsis.
80        static long long test(...);
81        static FromType object; // helper object to handle private c'tor and d'tor
82    public:
83        // test(object) only has 'long long' return type iff the compiler doesn't choose test(...)
84        enum { exists = (sizeof(test(object)) == sizeof(char)) };
85    };
86}
[1505]87
[2710]88#ifdef ORXONOX_COMPILER_MSVC
[2087]89#  pragma warning(pop)
90#endif
[1505]91
92
[2087]93////////////////////////////////////
94//// ACTUAL CONVERSION SEQUENCE ////
95////////////////////////////////////
96/*
97    There is a distinct priority when choosing the right conversion function:
98    Overwrite:
99    1. (Partial) template specialisation of ConverterExplicit::convert()
100    Fallbacks:
101    2. Any possible implicit conversion. This includes 'FooBar' --> 'int' if FooBar defines operator float().
102    3. Global or member operators for stringstream when converting from or to std::string (or FROM const char*)
103    4. (Partial) template specialisation of ConverterFallback::convert()
104    5. Function that simply displays "Could not convert value" with type information obtained from typeid().
[1505]105
[2087]106    Notes:
107    There has to be an exact type match when using template specialisations.
108    Template specialisations can be defined after including this file. Any implicit cast function or iostream
109    operator has to be declared BEFORE this file gets parsed.
[1505]110
[2087]111    Defining your own functions:
112    There are obviously 4 ways to specifiy a user defined conversion. What should I use?
[1505]113
[2087]114    Usually, ConverterFallback fits quite well. You won't have to deal with the conversion from
115    'MyClass' to 'MyClass' by using another explicit template specialisation to avoid ambiguities.
[1505]116
[2087]117    However if you want to overwrite an implicit conversion or an iostream operator, you really need to
118    make use of ConverterExplicit.
119*/
120
[2171]121namespace orxonox
[1505]122{
[3196]123    namespace detail
[2171]124    {
125        //! Little template that maps integers to entire types (Alexandrescu 2001)
126        template <int I>
127        struct Int2Type { };
128    }
[1505]129
130
[2171]131    ///////////////////
132    // No Conversion //
133    ///////////////////
[1505]134
[2171]135    // Default template. No conversion available at all.
136    template <class FromType, class ToType>
137    struct ConverterFallback
[1505]138    {
[3196]139        FORCEINLINE static bool convert(ToType* output, const FromType& input)
[2171]140        {
141            COUT(2) << "Could not convert value of type " << typeid(FromType).name()
142                    << " to type " << typeid(ToType).name() << std::endl;
143            return false;
144        }
145    };
[2087]146
[2171]147    // If all else fails, try a dynamic_cast for pointer types.
148    template <class FromType, class ToType>
149    struct ConverterFallback<FromType*, ToType*>
[1505]150    {
[3196]151        FORCEINLINE static bool convert(ToType** output, FromType* const input)
[2087]152        {
[2171]153            ToType* temp = dynamic_cast<ToType*>(input);
154            if (temp)
155            {
156                *output = temp;
157                return true;
158            }
159            else
160                return false;
[2087]161        }
[2171]162    };
163}
[1505]164
165
[2087]166///////////////////////
167// ConverterFallback //
168///////////////////////
169
170// Default template for stringstream
171template <class FromType, class ToType>
172struct ConverterStringStream
[1505]173{
[3196]174    FORCEINLINE static bool convert(ToType* output, const FromType& input)
[1505]175    {
[2171]176        return orxonox::ConverterFallback<FromType, ToType>::convert(output, input);
[1505]177    }
178};
179
180
181/////////////
[2087]182// OStream //
[1505]183/////////////
184
[2087]185namespace fallbackTemplates
[1505]186{
[2087]187    template <class FromType>
[3196]188    FORCEINLINE bool operator <<(std::ostream& outstream,  const FromType& input)
[2087]189    {
190        std::string temp;
[2171]191        if (orxonox::ConverterFallback<FromType, std::string>::convert(&temp, input))
[2087]192        {
193            std::operator <<(outstream, temp);
194            return true;
195        }
196        else
197            return false;
198    }
199}
[1505]200
[2087]201// template that evaluates whether we can convert to std::string via ostringstream
[1505]202template <class FromType>
[2087]203struct ConverterStringStream<FromType, std::string>
[1505]204{
[3196]205    FORCEINLINE static bool convert(std::string* output, const FromType& input)
[1505]206    {
[2087]207        using namespace fallbackTemplates;
208        // this operator call only chooses fallbackTemplates::operator<< if there's no other fitting function
[1505]209        std::ostringstream oss;
210        if (oss << input)
211        {
212            (*output) = oss.str();
213            return true;
214        }
215        else
216            return false;
217    }
218};
219
[2087]220
221/////////////
222// IStream //
223/////////////
224
225namespace fallbackTemplates
[1625]226{
[2087]227    template <class ToType>
[3196]228    FORCEINLINE bool operator >>(std::istream& instream, ToType& output)
[2087]229    {
[2171]230        return orxonox::ConverterFallback<std::string, ToType>
[2087]231            ::convert(&output, static_cast<std::istringstream&>(instream).str());
232    }
[1625]233}
234
[2087]235// template that evaluates whether we can convert from std::string via ostringstream
[1505]236template <class ToType>
[2087]237struct ConverterStringStream<std::string, ToType>
[1505]238{
[3196]239    FORCEINLINE static bool convert(ToType* output, const std::string& input)
[1505]240    {
[2087]241        using namespace fallbackTemplates;
[1505]242        std::istringstream iss(input);
[2087]243        // this operator call only chooses fallbackTemplates::operator>> if there's no other fitting function
[1505]244        if (iss >> (*output))
[2087]245        {
[1505]246            return true;
[2087]247        }
[1505]248        else
249            return false;
250    }
251};
252
[2171]253namespace orxonox
[1625]254{
[1505]255
[2171]256    ///////////////////
257    // Implicit Cast //
258    ///////////////////
[1625]259
[2171]260    // implicit cast not possible, try stringstream conversion next
261    template <class FromType, class ToType>
[3196]262    FORCEINLINE bool convertImplicitely(ToType* output, const FromType& input, detail::Int2Type<false>)
[1505]263    {
[2171]264        return ConverterStringStream<FromType, ToType>::convert(output, input);
[1505]265    }
266
[2171]267    // We can cast implicitely
268    template <class FromType, class ToType>
[3196]269    FORCEINLINE bool convertImplicitely(ToType* output, const FromType& input, detail::Int2Type<true>)
[2171]270    {
271        (*output) = static_cast<ToType>(input);
[2087]272        return true;
[1505]273    }
274
275
[2171]276    ////////////////////////////////
277    // ConverterExplicit Fallback //
278    ////////////////////////////////
[1505]279
[2171]280    // Default template if no specialisation is available
281    template <class FromType, class ToType>
282    struct ConverterExplicit
283    {
[3196]284        FORCEINLINE static bool convert(ToType* output, const FromType& input)
[2171]285        {
286            // Try implict cast and probe first. If a simple cast is not possible, it will not compile
287            // We therefore have to out source it into another template function
288            const bool probe = ImplicitConversion<FromType, ToType>::exists;
[3196]289            return convertImplicitely(output, input, detail::Int2Type<probe>());
[2171]290        }
291    };
[2087]292
293
[2171]294    //////////////////////
295    // Public Functions //
296    //////////////////////
[2087]297
[2171]298    /**
299    @brief
300        Converts any value to any other as long as there exists a conversion.
301        Otherwise, the conversion will generate a runtime warning and return false.
302        For information about the different conversion methods (user defined too), see the section
303        'Actual conversion sequence' in this file above.
304    */
305    template <class FromType, class ToType>
[3196]306    FORCEINLINE bool convertValue(ToType* output, const FromType& input)
[2171]307    {
308        return ConverterExplicit<FromType, ToType>::convert(output, input);
309    }
[2087]310
[2171]311    // Calls convertValue and returns true if the conversion was successful.
312    // Otherwise the fallback is used.
313    /**
314    @brief
315        Converts any value to any other as long as there exists a conversion.
316        Otherwise, the conversion will generate a runtime warning and return false.
317        For information about the different conversion methods (user defined too), see the section
318        'Actual conversion sequence' in this file above.
319        If the conversion doesn't succeed, 'fallback' is written to '*output'.
320    @param fallback
321        A default value that gets written to '*output' if there is no conversion.
322    */
323    template<class FromType, class ToType>
[3196]324    FORCEINLINE bool convertValue(ToType* output, const FromType& input, const ToType& fallback)
[1625]325    {
[2171]326        if (convertValue(output, input))
327            return true;
328        else
329        {
330            (*output) = fallback;
331            return false;
332        }
[1625]333    }
334
[2171]335    // Directly returns the converted value, even if the conversion was not successful.
336    template<class FromType, class ToType>
[3196]337    FORCEINLINE ToType getConvertedValue(const FromType& input)
[1505]338    {
[2171]339        ToType output;
340        convertValue(&output, input);
341        return output;
[1505]342    }
[2171]343
344    // Directly returns the converted value, but uses the fallback on failure.
345    template<class FromType, class ToType>
[3196]346    FORCEINLINE ToType getConvertedValue(const FromType& input, const ToType& fallback)
[1505]347    {
[2171]348        ToType output;
349        convertValue(&output, input, fallback);
350        return output;
[1505]351    }
[2171]352
353    // Like getConvertedValue, but the template argument order is in reverse.
354    // That means you can call it exactly like static_cast<ToType>(fromTypeValue).
355    template<class ToType, class FromType>
[3196]356    FORCEINLINE ToType multi_cast(const FromType& input)
[1505]357    {
[2171]358        ToType output;
359        convertValue(&output, input);
360        return output;
[1505]361    }
362
[2171]363    ////////////////////////////////
364    // Special string conversions //
365    ////////////////////////////////
366
367    // Delegate conversion from const char* to std::string
368    template <class ToType>
369    struct ConverterExplicit<const char*, ToType>
[1625]370    {
[3196]371        FORCEINLINE static bool convert(ToType* output, const char* input)
[1625]372        {
[2171]373            return convertValue<std::string, ToType>(output, input);
[1625]374        }
[2171]375    };
376
377    // These conversions would exhibit ambiguous << or >> operators when using stringstream
378    template <>
379    struct ConverterExplicit<char, std::string>
380    {
[3196]381        FORCEINLINE static bool convert(std::string* output, const char input)
[1625]382        {
[2171]383            *output = std::string(1, input);
384            return true;
[1625]385        }
[2171]386    };
387    template <>
388    struct ConverterExplicit<unsigned char, std::string>
389    {
[3196]390        FORCEINLINE static bool convert(std::string* output, const unsigned char input)
[2171]391        {
392            *output = std::string(1, input);
393            return true;
394        }
395    };
396    template <>
397    struct ConverterExplicit<std::string, char>
398    {
[3196]399        FORCEINLINE static bool convert(char* output, const std::string input)
[2171]400        {
401            if (input != "")
402                *output = input[0];
403            else
404                *output = '\0';
405            return true;
406        }
407    };
408    template <>
409    struct ConverterExplicit<std::string, unsigned char>
410    {
[3196]411        FORCEINLINE static bool convert(unsigned char* output, const std::string input)
[2171]412        {
413            if (input != "")
414                *output = input[0];
415            else
416                *output = '\0';
417            return true;
418        }
419    };
[1625]420
[2171]421
422    // bool to std::string
423    template <>
424    struct ConverterExplicit<bool, std::string>
425    {
[3196]426        FORCEINLINE static bool convert(std::string* output, const bool& input)
[2171]427        {
428            if (input)
429              *output = "true";
430            else
431              *output = "false";
[2662]432            return true;
[2171]433        }
434    };
[1625]435
[2171]436    // std::string to bool
437    template <>
438    struct ConverterExplicit<std::string, bool>
439    {
440        static bool convert(bool* output, const std::string& input)
441        {
442            std::string stripped = getLowercase(removeTrailingWhitespaces(input));
443            if (stripped == "true" || stripped == "on" || stripped == "yes")
444            {
445              *output = true;
446              return true;
447            }
448            else if (stripped == "false" || stripped == "off" || stripped == "no")
449            {
450              *output = false;
451              return true;
452            }
453
454            std::istringstream iss(input);
455            if (iss >> (*output))
456                return true;
457            else
458                return false;
459        }
460    };
461}
462
[1052]463#endif /* _Convert_H__ */
Note: See TracBrowser for help on using the repository browser.