Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/consolecommands3/src/libraries/util/Convert.h @ 7782

Last change on this file since 7782 was 7179, checked in by landauf, 14 years ago

merged consolecommands2 to consolecommands3

  • Property svn:eol-style set to native
File size: 13.0 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
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:
23 *      Reto Grieder
24 *      Fabian 'x3n' Landau
25 *      Benjamin Grauer
26 *   Co-authors:
27 *      ...
28 */
29
30/*!
31    @file
32    @brief Definition and Implementation of the Convert class.
33*/
34
35#ifndef _Converter_H__
36#define _Converter_H__
37
38#include "UtilPrereqs.h"
39
40#include <string>
41#include <sstream>
42#include <typeinfo>
43
44#include "Debug.h"
45#include "TemplateUtils.h"
46
47////////////////////////////////////
48//// ACTUAL CONVERSION SEQUENCE ////
49////////////////////////////////////
50/*
51    There is a distinct priority when choosing the right conversion function:
52    Overwrite:
53    1. (Partial) template specialisation of ConverterExplicit::convert()
54    Fallbacks:
55    2. Any possible implicit conversion. This includes 'FooBar' --> 'int' if FooBar defines operator float().
56    3. Global or member operators for stringstream when converting from or to std::string (or FROM const char*)
57    4. (Partial) template specialisation of ConverterFallback::convert()
58    5. Function that simply displays "Could not convert value" with type information obtained from typeid().
59
60    Notes:
61    There has to be an exact type match when using template specialisations.
62    Template specialisations can be defined after including this file. Any implicit cast function or iostream
63    operator has to be declared BEFORE this file gets parsed.
64
65    Defining your own functions:
66    There are obviously 4 ways to specify a user defined conversion. What should you use?
67
68    Usually, ConverterFallback fits quite well. You won't have to deal with the conversion from
69    'MyClass' to 'MyClass' by using another explicit template specialisation to avoid ambiguities.
70
71    However if you want to overwrite an implicit conversion or an iostream operator, you really need to
72    make use of ConverterExplicit. We have to do this for the Ogre classes for instance because they
73    define stream operators we don't particulary like.
74*/
75
76namespace orxonox
77{
78    namespace detail
79    {
80        //! Little template that maps integers to entire types (Alexandrescu 2001)
81        template <int I>
82        struct Int2Type { };
83    }
84
85
86    ///////////////////
87    // No Conversion //
88    ///////////////////
89
90    // Default template. No conversion available at all.
91    template <class FromType, class ToType>
92    struct ConverterFallback
93    {
94        FORCEINLINE static bool convert(ToType* output, const FromType& input)
95        {
96            COUT(2) << "Could not convert value of type " << typeid(FromType).name()
97                    << " to type " << typeid(ToType).name() << std::endl;
98            return false;
99        }
100    };
101
102    // If all else fails, try a dynamic_cast for pointer types.
103    template <class FromType, class ToType>
104    struct ConverterFallback<FromType*, ToType*>
105    {
106        FORCEINLINE static bool convert(ToType** output, FromType* const input)
107        {
108            ToType* temp = dynamic_cast<ToType*>(input);
109            if (temp)
110            {
111                *output = temp;
112                return true;
113            }
114            else
115                return false;
116        }
117    };
118
119    ////////////
120    // upcast //
121    ////////////
122    namespace detail
123    {
124        // perform a static cast if ToType is a base of FromType
125        template<class ToType, class FromType>
126        FORCEINLINE ToType upcast(FromType input, detail::Int2Type<true>)
127        {
128            return static_cast<ToType>(input);
129        }
130
131        // return zero if ToType is not a base of FromType
132        template<class ToType, class FromType>
133        FORCEINLINE ToType upcast(FromType input, detail::Int2Type<false>)
134        {
135            return 0;
136        }
137    }
138
139    // performs an upcast if ToType is a base of FromType, returns zero otherwise
140    template <class ToType, class FromType>
141    FORCEINLINE ToType upcast(FromType input)
142    {
143        enum { probe = ImplicitConversion<FromType, ToType>::exists };
144        return detail::upcast<ToType, FromType>(input, detail::Int2Type<probe>());
145    }
146}
147
148
149///////////////////////
150// ConverterFallback //
151///////////////////////
152
153// Default template for stringstream
154template <class FromType, class ToType>
155struct ConverterStringStream
156{
157    FORCEINLINE static bool convert(ToType* output, const FromType& input)
158    {
159        return orxonox::ConverterFallback<FromType, ToType>::convert(output, input);
160    }
161};
162
163
164/////////////
165// OStream //
166/////////////
167
168namespace fallbackTemplates
169{
170    template <class FromType>
171    FORCEINLINE bool operator <<(std::ostream& outstream,  const FromType& input)
172    {
173        std::string temp;
174        if (orxonox::ConverterFallback<FromType, std::string>::convert(&temp, input))
175        {
176            std::operator <<(outstream, temp);
177            return true;
178        }
179        else
180            return false;
181    }
182}
183
184// template that evaluates whether we can convert to std::string via ostringstream
185template <class FromType>
186struct ConverterStringStream<FromType, std::string>
187{
188    FORCEINLINE static bool convert(std::string* output, const FromType& input)
189    {
190        using namespace fallbackTemplates;
191        // this operator call only chooses fallbackTemplates::operator<< if there's no other fitting function
192        std::ostringstream oss;
193        if (oss << input)
194        {
195            (*output) = oss.str();
196            return true;
197        }
198        else
199            return false;
200    }
201};
202
203
204/////////////
205// IStream //
206/////////////
207
208namespace fallbackTemplates
209{
210    template <class ToType>
211    FORCEINLINE bool operator >>(std::istream& instream, ToType& output)
212    {
213        return orxonox::ConverterFallback<std::string, ToType>
214            ::convert(&output, static_cast<std::istringstream&>(instream).str());
215    }
216}
217
218// template that evaluates whether we can convert from std::string via ostringstream
219template <class ToType>
220struct ConverterStringStream<std::string, ToType>
221{
222    FORCEINLINE static bool convert(ToType* output, const std::string& input)
223    {
224        using namespace fallbackTemplates;
225        std::istringstream iss(input);
226        // this operator call only chooses fallbackTemplates::operator>> if there's no other fitting function
227        if (iss >> (*output))
228        {
229            return true;
230        }
231        else
232            return false;
233    }
234};
235
236namespace orxonox
237{
238
239    ///////////////////
240    // Implicit Cast //
241    ///////////////////
242
243    // implicit cast not possible, try stringstream conversion next
244    template <class FromType, class ToType>
245    FORCEINLINE bool convertImplicitely(ToType* output, const FromType& input, detail::Int2Type<false>)
246    {
247        return ConverterStringStream<FromType, ToType>::convert(output, input);
248    }
249
250    // We can cast implicitely
251    template <class FromType, class ToType>
252    FORCEINLINE bool convertImplicitely(ToType* output, const FromType& input, detail::Int2Type<true>)
253    {
254        (*output) = static_cast<ToType>(input);
255        return true;
256    }
257
258
259    ////////////////////////////////
260    // ConverterExplicit Fallback //
261    ////////////////////////////////
262
263    // Default template if no specialisation is available
264    template <class FromType, class ToType>
265    struct ConverterExplicit
266    {
267        enum { probe = ImplicitConversion<FromType, ToType>::exists };
268        FORCEINLINE static bool convert(ToType* output, const FromType& input)
269        {
270            // Try implict cast and probe first. If a simple cast is not possible, it will not compile
271            // We therefore have to out source it into another template function
272            return convertImplicitely(output, input, detail::Int2Type<probe>());
273        }
274    };
275
276
277    //////////////////////
278    // Public Functions //
279    //////////////////////
280
281    /**
282    @brief
283        Converts any value to any other as long as there exists a conversion.
284        Otherwise, the conversion will generate a runtime warning and return false.
285        For information about the different conversion methods (user defined too), see the section
286        'Actual conversion sequence' in this file above.
287    */
288    template <class FromType, class ToType>
289    FORCEINLINE bool convertValue(ToType* output, const FromType& input)
290    {
291        return ConverterExplicit<FromType, ToType>::convert(output, input);
292    }
293
294    // Calls convertValue and returns true if the conversion was successful.
295    // Otherwise the fallback is used.
296    /**
297    @brief
298        Converts any value to any other as long as there exists a conversion.
299        Otherwise, the conversion will generate a runtime warning and return false.
300        For information about the different conversion methods (user defined too), see the section
301        'Actual conversion sequence' in this file above.
302        If the conversion doesn't succeed, 'fallback' is written to '*output'.
303    @param fallback
304        A default value that gets written to '*output' if there is no conversion.
305    */
306    template<class FromType, class ToType>
307    FORCEINLINE bool convertValue(ToType* output, const FromType& input, const ToType& fallback)
308    {
309        if (convertValue(output, input))
310            return true;
311        else
312        {
313            (*output) = fallback;
314            return false;
315        }
316    }
317
318    // Directly returns the converted value, even if the conversion was not successful.
319    template<class FromType, class ToType>
320    FORCEINLINE ToType getConvertedValue(const FromType& input)
321    {
322        ToType output;
323        convertValue(&output, input);
324        return output;
325    }
326
327    // Directly returns the converted value, but uses the fallback on failure.
328    template<class FromType, class ToType>
329    FORCEINLINE ToType getConvertedValue(const FromType& input, const ToType& fallback)
330    {
331        ToType output;
332        convertValue(&output, input, fallback);
333        return output;
334    }
335
336    // Like getConvertedValue, but the template argument order is in reverse.
337    // That means you can call it exactly like static_cast<ToType>(fromTypeValue).
338    template<class ToType, class FromType>
339    FORCEINLINE ToType multi_cast(const FromType& input)
340    {
341        ToType output;
342        convertValue(&output, input);
343        return output;
344    }
345
346    ////////////////////////////////
347    // Special string conversions //
348    ////////////////////////////////
349
350    // Delegate conversion from const char* to std::string
351    template <class ToType>
352    struct ConverterExplicit<const char*, ToType>
353    {
354        FORCEINLINE static bool convert(ToType* output, const char* input)
355        {
356            return convertValue<std::string, ToType>(output, input);
357        }
358    };
359
360    // These conversions would exhibit ambiguous << or >> operators when using stringstream
361    template <>
362    struct ConverterExplicit<char, std::string>
363    {
364        FORCEINLINE static bool convert(std::string* output, const char input)
365        {
366            *output = input;
367            return true;
368        }
369    };
370    template <>
371    struct ConverterExplicit<unsigned char, std::string>
372    {
373        FORCEINLINE static bool convert(std::string* output, const unsigned char input)
374        {
375            *output = input;
376            return true;
377        }
378    };
379    template <>
380    struct ConverterExplicit<std::string, char>
381    {
382        FORCEINLINE static bool convert(char* output, const std::string& input)
383        {
384            if (!input.empty())
385                *output = input[0];
386            else
387                *output = '\0';
388            return true;
389        }
390    };
391    template <>
392    struct ConverterExplicit<std::string, unsigned char>
393    {
394        FORCEINLINE static bool convert(unsigned char* output, const std::string& input)
395        {
396            if (!input.empty())
397                *output = input[0];
398            else
399                *output = '\0';
400            return true;
401        }
402    };
403
404
405    // bool to std::string
406    template <>
407    struct ConverterExplicit<bool, std::string>
408    {
409        FORCEINLINE static bool convert(std::string* output, const bool& input)
410        {
411            if (input)
412              *output = "true";
413            else
414              *output = "false";
415            return true;
416        }
417    };
418
419    // std::string to bool
420    template <>
421    struct _UtilExport ConverterExplicit<std::string, bool>
422    {
423        static bool convert(bool* output, const std::string& input);
424    };
425}
426
427#endif /* _Convert_H__ */
Note: See TracBrowser for help on using the repository browser.