Simpatico  v1.10
Setable.h
1 #ifndef UTIL_SETABLE_H
2 #define UTIL_SETABLE_H
3 
4 /*
5 * Util Package - C++ Utilities for Scientific Computation
6 *
7 * Copyright 2010 - 2017, The Regents of the University of Minnesota
8 * Distributed under the terms of the GNU General Public License.
9 */
10 
11 #include <util/global.h>
12 
13 namespace Util
14 {
15 
37  template <class T>
38  class Setable
39  {
40 
41  public:
42 
47  : value_(),
48  isSet_(false)
49  {}
50 
56  Setable(const Setable<T>& other)
57  : value_(other.value_),
58  isSet_(other.isSet_)
59  {}
60 
66  explicit Setable(const T& value)
67  : value_(value),
68  isSet_(true)
69  {}
70 
77  {
78  if (this != &other) {
79  isSet_ = other.isSet_;
80  if (other.isSet_) {
81  value_ = other.value_;
82  }
83  }
84  return *this;
85  }
86 
96  {
97  value_ = value;
98  isSet_ = true;
99  return *this;
100  }
101 
107  void set(const T& value)
108  {
109  value_ = value;
110  isSet_ = true;
111  }
112 
116  void unset()
117  { isSet_ = false; }
118 
124  bool isSet() const
125  { return isSet_; }
126 
132  const T& value() const
133  {
134  if (!isSet_) {
135  UTIL_THROW("Attempt to return unknown value.");
136  }
137  return value_;
138  }
139 
140  #ifdef UTIL_MPI
141 
148  bool isValid(MPI::Intracomm& communicator) const;
149  #endif
150 
151  private:
152 
154  T value_;
155 
157  bool isSet_;
158 
159  };
160 
161  #ifdef UTIL_MPI
162  template <typename T>
163  bool Setable<T>::isValid(MPI::Intracomm& communicator) const
164  {
165  int isSet = (int)isSet_;
166  int total = 0;
167  communicator.Allreduce(&isSet, &total, 1, MPI::INT, MPI::SUM);
168  int nproc = communicator.Get_size();
169  if (isSet_ && total != nproc) {
170  UTIL_THROW("Inconsistent settings");
171  }
172  if ((!isSet_) && total != 0) {
173  UTIL_THROW("Inconsistent settings");
174  }
175  return true;
176  }
177  #endif
178 
179 }
180 #endif
bool isSet() const
Is this object set (is the value known)?
Definition: Setable.h:124
Setable()
Default constructor.
Definition: Setable.h:46
Template for a value that can be set or declared null (i.e., unknown).
Definition: Setable.h:38
File containing preprocessor macros for error handling.
Setable(const T &value)
Construct from T value (explicit).
Definition: Setable.h:66
const T & value() const
Return value (if set).
Definition: Setable.h:132
#define UTIL_THROW(msg)
Macro for throwing an Exception, reporting function, file and line number.
Definition: global.h:51
bool isValid(MPI::Intracomm &communicator) const
Test consistency of states on different processors.
Definition: Setable.h:163
Utility classes for scientific computation.
Definition: accumulators.mod:1
Setable(const Setable< T > &other)
Copy constructor.
Definition: Setable.h:56
void unset()
Unset the value (mark as unknown).
Definition: Setable.h:116
Setable< T > & operator=(const Setable< T > &other)
Assignment from another Setable<T> object.
Definition: Setable.h:76