IMP  2.3.1
The Integrative Modeling Platform
Showable.h
Go to the documentation of this file.
1 /**
2  * \file IMP/base/Showable.h \brief IO support.
3  *
4  * Copyright 2007-2014 IMP Inventors. All rights reserved.
5  *
6  */
7 
8 #ifndef IMPBASE_SHOWABLE_H
9 #define IMPBASE_SHOWABLE_H
10 
11 #include <IMP/base/base_config.h>
12 // do not include anything else from IMP
13 #include <sstream>
14 #include <iostream>
15 #include <utility>
16 #include <sstream>
17 
18 IMPBASE_BEGIN_NAMESPACE
19 /** This is a helper class to aid in output of the
20  various classes in \imp.
21  To support output to streams, a class can use the
22  IMP_SHOWABLE macros
23  to define an implicit conversion to Showable.
24  */
25 class IMPBASEEXPORT Showable {
26  std::string str_;
27  template <class T>
28  void show_ptr(const T *o) {
29  std::ostringstream oss;
30  if (o) {
31  oss << '"' << o->get_name() << '"';
32  } else {
33  oss << "nullptr";
34  }
35  str_ = oss.str();
36  }
37 
38  public:
39  template <class T>
40  explicit Showable(const T &t) {
41  std::ostringstream oss;
42  oss << t;
43  str_ = oss.str();
44  }
45  template <class T>
46  explicit Showable(const T *o) {
47  show_ptr(o);
48  }
49  template <class T>
50  explicit Showable(T *o) {
51  show_ptr(o);
52  }
53  IMP_CXX11_DEFAULT_COPY_CONSTRUCTOR(Showable);
54  Showable(const std::string &str) : str_(str) {}
55  Showable(const char *str) : str_(str) {}
56  template <class T, class TT>
57  Showable(const std::pair<T, TT> &p) {
58  std::ostringstream oss;
59  oss << "(" << p.first << ", " << p.second << ")";
60  str_ = oss.str();
61  }
62  std::string get_string() const { return str_; }
63  ~Showable();
64 };
65 
66 inline std::ostream &operator<<(std::ostream &out, const Showable &s) {
67  out << s.get_string();
68  return out;
69 }
70 
71 IMPBASE_END_NAMESPACE
72 
73 #endif /* IMPBASE_SHOWABLE_H */