IMP logo
IMP Reference Guide  2.20.0
The Integrative Modeling Platform
Showable.h
Go to the documentation of this file.
1 /**
2  * \file IMP/Showable.h
3  * \brief Helper class to aid in output of \imp classes to streams.
4  *
5  * Copyright 2007-2022 IMP Inventors. All rights reserved.
6  *
7  */
8 
9 #ifndef IMPKERNEL_SHOWABLE_H
10 #define IMPKERNEL_SHOWABLE_H
11 
12 #include <IMP/kernel_config.h>
13 // do not include anything else from IMP
14 #include <sstream>
15 #include <iostream>
16 #include <utility>
17 #include <sstream>
18 
19 IMPKERNEL_BEGIN_NAMESPACE
20 
21 //! Helper class to aid in output of \imp classes to streams.
22 /** To support output to streams, a class can use the IMP_SHOWABLE macros
23  to define an implicit conversion to Showable.
24  */
25 class IMPKERNELEXPORT 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 IMPKERNEL_END_NAMESPACE
72 
73 #endif /* IMPKERNEL_SHOWABLE_H */
Helper class to aid in output of IMP classes to streams.
Definition: Showable.h:25