RMF
Nullable.h
Go to the documentation of this file.
1/**
2 * \file RMF/Nullable.h
3 * \brief A helper class for allowing nice return of possibly null values.
4 *
5 * Copyright 2007-2022 IMP Inventors. All rights reserved.
6 *
7 */
8
9#ifndef RMF_NULLABLE_H
10#define RMF_NULLABLE_H
11
12#include "RMF/config.h"
13#include "traits.h"
15#include "exceptions.h"
16#include <limits>
17
18RMF_ENABLE_WARNINGS
19
20namespace RMF {
21
22/** \brief Return a possibly null value.
23
24 Return a value as returned by RMF with the additional ability to check if it
25 is the null value. These get converted to plain values or `None` in python.
26 \note they should never be stored.
27*/
28template <class T>
29class Nullable {
30 typename Traits<T>::ReturnType v_;
31 std::string get_string() const {
32 if (get_is_null())
33 return "<null>";
34 else {
35 std::ostringstream oss;
36 oss << v_;
37 return oss.str();
38 }
39 }
40
41 public:
42 Nullable(const Nullable& o) : v_(o.v_) {}
43#ifndef SWIG
44 Nullable(typename Traits<T>::ReturnType v) : v_(v) {}
45 /** \pre !get_is_null() */
46 operator typename Traits<T>::ReturnType() const { return get(); }
47 /** \pre !get_is_null() */
48 typename Traits<T>::ReturnType get() const {
49 RMF_USAGE_CHECK(!get_is_null(), "Can't convert null value.");
50 return v_;
51 }
52#else
53 T get() const;
54#endif
55 bool get_is_null() const { return Traits<T>::get_is_null_value(v_); }
56
57#ifndef IMP_DOXYGEN
58 /** For python since it nicely becomes None. */
59 const T* get_ptr() const {
60 if (get_is_null())
61 return nullptr;
62 else
63 return &v_;
64 }
65#endif
66#if !defined(RMF_DOXYGEN) && !defined(SWIG)
67 void show(std::ostream& out) const { out << get_string(); }
68#endif
69};
70
71#if !defined(SWIG) && !defined(RMF_DOXYGEN)
72template <class Traits>
73inline std::ostream& operator<<(std::ostream& out, Nullable<Traits> null) {
74 null.show(out);
75 return out;
76}
77#endif
78
79} /* namespace RMF */
80
81RMF_DISABLE_WARNINGS
82
83#endif /* RMF_NULLABLE_H */
Return a possibly null value.
Definition Nullable.h:29
const T * get_ptr() const
Definition Nullable.h:59
Traits< T >::ReturnType get() const
Definition Nullable.h:48
Declarations of the various exception types.
Various general useful macros for IMP.
The namespace for all functionality in the library.
Traits classes describing how RMF uses types for storing data.
Definition traits.h:31
Handle read/write of Model data from/to files.