Formatter.h 1.37 KB
Newer Older
Bryan Berthou's avatar
refs#16  
Bryan Berthou committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef FORMATTER_H
#define FORMATTER_H

/**
 * @file Formatter.h
 * @author Bryan BERTHOU (SPhN / CEA Saclay)
 * @author <contibutor> http://stackoverflow.com/questions/12261915/howto-throw-stdexceptions-with-variable-messages/12262626#12262626
 * @date 16 September 2014
 * @version 1.0
 */

#include <iomanip>
#include <sstream>
#include <string>
Nabil Chouika's avatar
refs#16    
Nabil Chouika committed
15
#include <limits>
Bryan Berthou's avatar
refs#16  
Bryan Berthou committed
16
17
18

namespace ElemUtils {

Bryan Berthou's avatar
refs#16    
Bryan Berthou committed
19
20
21
22
/** @class Formatter
 *
 * @brief
 */
Bryan Berthou's avatar
refs#16  
Bryan Berthou committed
23
24
25
26
class Formatter {
public:
    Formatter() {
        // use to print full precision double
Nabil Chouika's avatar
refs#16    
Nabil Chouika committed
27
        m_stream << std::setprecision(std::numeric_limits<double>::digits10);
Bryan Berthou's avatar
refs#16  
Bryan Berthou committed
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
    }

    ~Formatter() {
    }

    template<typename Type>
    Formatter & operator <<(const Type & value) {
        m_stream << value;
        return *this;
    }

    std::string str() const {
        return m_stream.str();
    }

Nabil Chouika's avatar
refs#16    
Nabil Chouika committed
43
44
45
    /**
     * Automatic cast to string.
     */
Bryan Berthou's avatar
refs#16  
Bryan Berthou committed
46
47
48
49
    operator std::string() const {
        return m_stream.str();
    }

Nabil Chouika's avatar
refs#16    
Nabil Chouika committed
50
51
52
53
54
55
56
    /**
     * Automatic cast to stringstream.
     */
    operator std::stringstream&() {
        return m_stream;
    }

Bryan Berthou's avatar
refs#16  
Bryan Berthou committed
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
    enum ConvertToString {
        to_str
    };

    std::string operator >>(ConvertToString) {
        return m_stream.str();
    }

    void print();

private:
    std::stringstream m_stream;

    Formatter(const Formatter &);
    Formatter & operator =(Formatter &);
};

} // namespace ElemUtils

#endif /* FORMATTER_H */