IMP  2.0.0
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-2013 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 
20 /** This is a helper class to aid in output of the various classes in \imp.
21  To support output to streams, a class can use the IMP_SHOWABLE macros
22  to define an implicit conversion to Showable.
23 */
24 class IMPBASEEXPORT Showable {
25  std::string str_;
26  template <class T>
27  void show_ptr(const T*o) {
28  std::ostringstream oss;
29  if (o) {
30  oss << '"' << o->get_name() << '"';
31  } else {
32  oss << "nullptr";
33  }
34  str_=oss.str();
35  }
36 public:
37  template <class T>
38  explicit Showable(const T &t) {
39  std::ostringstream oss;
40  oss << t;
41  str_= oss.str();
42  }
43  template <class T>
44  explicit Showable(const T *o) {
45  show_ptr(o);
46  }
47  template <class T>
48  explicit Showable(T *o) {
49  show_ptr(o);
50  }
51  Showable(const std::string& str): str_(str){}
52  Showable(const char *str): str_(str){}
53  template <class T, class TT>
54  Showable(const std::pair<T, TT> &p) {
55  std::ostringstream oss;
56  oss << "(" << p.first << ", " << p.second << ")";
57  str_=oss.str();
58  }
59  std::string get_string() const {
60  return str_;
61  }
62  ~Showable();
63 };
64 
65 inline std::ostream &operator<<(std::ostream &out, const Showable &s) {
66  out << s.get_string();
67  return out;
68 }
69 
70 
71 IMPBASE_END_NAMESPACE
72 
73 #endif /* IMPBASE_SHOWABLE_H */