Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/libraries/util/Convert.h @ 11393

Last change on this file since 11393 was 11098, checked in by muemart, 9 years ago

Minor C++11 improvements:

  • Drop ImplicitConversion.h in favor of std::is_convertible.
  • Move constructor & assignment for MultiType and SubString. I'm not sure if the MultiType should convert types when moving. Currently it doesn't, because otherwise it would have no benefit over copying.
  • Use standard library functions for sleeping.
  • Property svn:eol-style set to native
File size: 15.5 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    @defgroup Convert Conversion functions
32    @ingroup Util
33*/
34
35/** Functions that convert values between different types.
36@file
37@ingroup Convert
38@par Usage
39    There are three ways to use the conversions depending on what you need. <br>
40    - For simply converting values without having to know whether the conversion
41      was successful (for instance float --> string), use orxonox::multi_cast
42      which effectively works exactly like static_cast, etc.
43      @code
44        float input = 42.0;
45        std::string output = multi_cast<std::string>(input);
46      @endcode
47    - If you care about whether the conversion was successful,
48      use orxonox::convertValue.
49      @code
50        std::string input("3.4");
51        float output;
52        bool success = convertValue(&output, input);
53      @endcode
54    - If you care about success and if you can also feed a fallback value,
55      use orxonox::convertValue.
56      @code
57        std::string input("3.4");
58        float output;
59        bool success = convertValue(&output, input, 0.0);
60      @endcode
61    - If success doesn't matter but you can feed a fallback value,
62      use orxonox::getConvertedValue.
63      @code
64        std::string input("3.4");
65        float output = getConvertedValue(input, 0.0);
66      @endcode
67@details
68    The back end of these functions are the actual implementations for the
69    specific conversions, for instance from Ogre::Vector3 to std::string and
70    vice versa. Some of them also use the iostream operators. <br>
71    The real deal is evaluating which function is needed for a conversion based
72    on the input and output type. But there are lots of catches in conjunction
73    with templates which explains why there are so many functions in this file.
74    <br> <br>
75@par Search Order
76    Finding the right function is governed by priority rules: <br>
77    -# (Partial) template specialisation of orxonox::ConverterExplicit::convert()
78    -# An implicit conversion. This includes 'FooBar' to 'int' if FooBar
79       defines operator int() or float().
80    -# Global or member operators for iostream when converting from or
81       to std::string (and FROM const char*)
82    -# (Partial) template specialisation of orxonox::ConverterFallback::convert()
83    -# Fallback function that displays "Could not convert value" with type
84       information obtained from typeid().
85@par Implementing conversion functions
86    To do that you probably need to know a thing or two about the types
87    involved. So, get ready with that. <br>
88    Usually the best way to do it is specialising of the orxonox::ConverterFallback
89    template, like this:
90    @code
91    template <>
92    struct _UtilExport ConverterFallback<std::string, MyType>
93    {
94        static bool convert(MyType* output, const std::string& input)
95        {
96           ...
97           return success;
98        }
99    };
100    @endcode
101    This piece of code converts an std::string to MyType and returns whether the
102    conversion was successful. You can also use partial specialisation.<br>
103    The advantage with orxonox::ConverterFallback is that it has a low priority
104    meaning that when there is an implicit conversion or an iostream method, that
105    comes first and you don't have to deal with it (and the accompanying
106    function call ambiguity). <br>
107    However sometimes you would like to explicitely replace such a conversion.
108    That's where orxonox::ConverterExplicit comes in handy (for instance we
109    replaced the operator << conversions for Ogre::VectorX with our own functions).
110@note
111    There has to be an exact type match when using template specialisations. <br>
112    Template specialisations can be defined after including this file.
113    But any implicit cast function or iostream operator has to be included
114    in this file!
115@par Understanding the Code
116    In order to understand how the templates work, it is probably best to study
117    the functions in order of calling. There are lots of comments explaining
118    what happens, but you'll need to understand a deal about partial template
119    specialisation and function headers are matched in C++.
120*/
121
122#ifndef _Converter_H__
123#define _Converter_H__
124
125#include "UtilPrereqs.h"
126
127#include <string>
128#include <sstream>
129#include <typeinfo>
130#include <type_traits>
131#include <loki/TypeManip.h>
132
133#include "Output.h"
134
135// disable warnings about possible loss of data
136#ifdef ORXONOX_COMPILER_MSVC
137#  pragma warning(push)
138#  pragma warning(disable:4244)
139#endif
140
141namespace orxonox
142{
143    ///////////////////
144    // No Conversion //
145    ///////////////////
146
147    /// Default template. No conversion available at all.
148    template <class FromType, class ToType>
149    struct ConverterFallback
150    {
151        ORX_FORCEINLINE static bool convert(ToType* /*output*/, const FromType& /*input*/)
152        {
153            orxout(internal_warning) << "Could not convert value of type " << typeid(FromType).name()
154                                     << " to type " << typeid(ToType).name() << endl;
155            return false;
156        }
157    };
158
159    /// If all else fails, try a dynamic_cast for pointer types.
160    template <class FromType, class ToType>
161    struct ConverterFallback<FromType*, ToType*>
162    {
163        ORX_FORCEINLINE static bool convert(ToType** output, FromType* const input)
164        {
165            ToType* temp = dynamic_cast<ToType*>(input);
166            if (temp)
167            {
168                *output = temp;
169                return true;
170            }
171            else
172                return false;
173        }
174    };
175}
176
177
178///////////////////////
179// ConverterFallback //
180///////////////////////
181
182/** Fallback template for stringstream
183@details
184    Neither FromType nor ToType was std::string, therefore
185    delegate to orxonox::ConverterFallback
186*/
187template <class FromType, class ToType>
188struct ConverterStringStream
189{
190    ORX_FORCEINLINE static bool convert(ToType* output, const FromType& input)
191    {
192        return orxonox::ConverterFallback<FromType, ToType>::convert(output, input);
193    }
194};
195
196
197/////////////
198// OStream //
199/////////////
200
201/// Extra namespace to avoid exposing the iostream operators in it
202namespace fallbackTemplates
203{
204    /// Fallback operator <<() (delegates to orxonox::ConverterFallback)
205    template <class FromType>
206    ORX_FORCEINLINE bool operator <<(std::ostream& outstream,  const FromType& input)
207    {
208        std::string temp;
209        if (orxonox::ConverterFallback<FromType, std::string>::convert(&temp, input))
210        {
211            std::operator <<(outstream, temp);
212            return true;
213        }
214        else
215            return false;
216    }
217}
218
219/// Template that evaluates whether we can convert to std::string via ostringstream
220template <class FromType>
221struct ConverterStringStream<FromType, std::string>
222{
223    ORX_FORCEINLINE static bool convert(std::string* output, const FromType& input)
224    {
225        using namespace fallbackTemplates;
226        // this operator call only chooses fallbackTemplates::operator<<()
227        // if there's no other fitting function
228        std::ostringstream oss;
229        // Note: std::ostream has operator!() to tell whether any error flag was set
230        if (oss << input)
231        {
232            (*output) = oss.str();
233            return true;
234        }
235        else
236            return false;
237    }
238};
239
240
241/////////////
242// IStream //
243/////////////
244
245namespace fallbackTemplates
246{
247    /// Fallback operator >>() (delegates to orxonox::ConverterFallback)
248    template <class ToType>
249    ORX_FORCEINLINE bool operator >>(std::istream& instream, ToType& output)
250    {
251        std::string input(static_cast<std::istringstream&>(instream).str());
252        return orxonox::ConverterFallback<std::string, ToType>::convert(&output, input);
253    }
254}
255
256/// Template that evaluates whether we can convert from std::string via istringstream
257template <class ToType>
258struct ConverterStringStream<std::string, ToType>
259{
260    ORX_FORCEINLINE static bool convert(ToType* output, const std::string& input)
261    {
262        using namespace fallbackTemplates;
263        // this operator call chooses fallbackTemplates::operator>>()
264        // only if there's no other fitting function
265        std::istringstream iss(input);
266        // Note: std::istream has operator!() to tell whether any error flag was set
267        if (iss >> (*output))
268        {
269            return true;
270        }
271        else
272            return false;
273    }
274};
275
276namespace orxonox
277{
278    ///////////////////
279    // Implicit Cast //
280    ///////////////////
281
282    /// %Template delegates to ::ConverterStringStream
283    template <class FromType, class ToType>
284    ORX_FORCEINLINE bool convertImplicitely(ToType* output, const FromType& input, Loki::Int2Type<false>)
285    {
286        return ConverterStringStream<FromType, ToType>::convert(output, input);
287    }
288
289    /// Makes an implicit cast from \a FromType to \a ToType
290    template <class FromType, class ToType>
291    ORX_FORCEINLINE bool convertImplicitely(ToType* output, const FromType& input, Loki::Int2Type<true>)
292    {
293        (*output) = static_cast<ToType>(input);
294        return true;
295    }
296
297
298    ////////////////////////////////
299    // ConverterExplicit Fallback //
300    ////////////////////////////////
301
302    /** Default template if no orxonox::ConverterExplicit is available
303    @details
304        Evaluates whether \a FromType can be implicitly converted to \a ToType
305        by the use the ImplicitConversion magic.
306    */
307    template <class FromType, class ToType>
308    struct ConverterExplicit
309    {
310        static constexpr bool probe = std::is_convertible<FromType, ToType>::value;
311        ORX_FORCEINLINE static bool convert(ToType* output, const FromType& input)
312        {
313            // Use the probe's value to delegate to the right function
314            return convertImplicitely(output, input, Loki::Int2Type<probe>());
315        }
316    };
317
318
319    //////////////////////
320    // Public Functions //
321    //////////////////////
322
323    /**
324    @brief
325        Converts any value to any other as long as there exists a conversion.
326    @details
327        Otherwise, the conversion will generate a runtime warning and return false.
328    @see Convert.h
329    @param output
330        A pointer to the variable where the converted value will be stored
331    @param input
332        The original value
333    */
334    template <class FromType, class ToType>
335    ORX_FORCEINLINE bool convertValue(ToType* output, const FromType& input)
336    {
337        return ConverterExplicit<FromType, ToType>::convert(output, input);
338    }
339
340    // Calls convertValue and returns true if the conversion was successful.
341    // Otherwise the fallback is used.
342    /**
343    @brief
344        Converts any value to any other as long as there exists a conversion.
345        Otherwise, the conversion will generate a runtime warning and return false.
346        If the conversion doesn't succeed, \a fallback is written to \a output.
347    @see Convert.h
348    @param output
349        A pointer to the variable where the converted value will be stored
350    @param input
351        The original value
352    @param fallback
353        A default value that gets written to '*output' if there is no conversion.
354    */
355    template<class FromType, class ToType>
356    ORX_FORCEINLINE bool convertValue(ToType* output, const FromType& input, const ToType& fallback)
357    {
358        if (convertValue(output, input))
359            return true;
360        else
361        {
362            (*output) = fallback;
363            return false;
364        }
365    }
366
367    /// Directly returns the converted value, but uses the fallback on failure. @see convertValue
368    template<class FromType, class ToType>
369    ORX_FORCEINLINE ToType getConvertedValue(const FromType& input, const ToType& fallback)
370    {
371        ToType output;
372        convertValue(&output, input, fallback);
373        return output;
374    }
375
376    /**
377    @brief
378        Converts any value to any other as long as there exists a conversion.
379    @details
380        Use exactly the way you use static_cast, etc. <br>
381        A failed conversion will return a default instance of \a ToType
382        (possibly uninitialised)
383    @see Convert.h
384    @param input
385        The original value
386    */
387    template<class ToType, class FromType>
388    ORX_FORCEINLINE ToType multi_cast(const FromType& input)
389    {
390        ToType output;
391        convertValue(&output, input);
392        return output;
393    }
394
395    ////////////////////////////////
396    // Special string conversions //
397    ////////////////////////////////
398
399    /// Delegates conversion from const char* to std::string
400    template <class ToType>
401    struct ConverterExplicit<const char*, ToType>
402    {
403        ORX_FORCEINLINE static bool convert(ToType* output, const char* input)
404        {
405            return convertValue<std::string, ToType>(output, input);
406        }
407    };
408
409    /// Conversion would exhibit ambiguous << or >> operators when using iostream
410    template <>
411    struct ConverterExplicit<char, std::string>
412    {
413        ORX_FORCEINLINE static bool convert(std::string* output, const char input)
414        {
415            *output = input;
416            return true;
417        }
418    };
419    /// Conversion would exhibit ambiguous << or >> operators when using iostream
420    template <>
421    struct ConverterExplicit<unsigned char, std::string>
422    {
423        ORX_FORCEINLINE static bool convert(std::string* output, const unsigned char input)
424        {
425            *output = input;
426            return true;
427        }
428    };
429    /// Conversion would exhibit ambiguous << or >> operators when using iostream
430    template <>
431    struct ConverterExplicit<std::string, char>
432    {
433        ORX_FORCEINLINE static bool convert(char* output, const std::string& input)
434        {
435            if (!input.empty())
436                *output = input[0];
437            else
438                *output = '\0';
439            return true;
440        }
441    };
442    /// Conversion would exhibit ambiguous << or >> operators when using iostream
443    template <>
444    struct ConverterExplicit<std::string, unsigned char>
445    {
446        ORX_FORCEINLINE static bool convert(unsigned char* output, const std::string& input)
447        {
448            if (!input.empty())
449                *output = input[0];
450            else
451                *output = '\0';
452            return true;
453        }
454    };
455
456
457    /// Conversion from bool to std::string
458    template <>
459    struct ConverterExplicit<bool, std::string>
460    {
461        ORX_FORCEINLINE static bool convert(std::string* output, const bool& input)
462        {
463            if (input)
464              *output = "true";
465            else
466              *output = "false";
467            return true;
468        }
469    };
470
471    /// Conversion from std::string to bool
472    template <>
473    struct _UtilExport ConverterExplicit<std::string, bool>
474    {
475        static bool convert(bool* output, const std::string& input);
476    };
477}
478
479// Reinstate warnings
480#ifdef ORXONOX_COMPILER_MSVC
481#  pragma warning(pop)
482#endif
483
484#endif /* _Convert_H__ */
Note: See TracBrowser for help on using the repository browser.