Mutable / Mutable / Validated.h

//=============================================================================
//
//D A templatised class to represent data which can be validated, for instance
//D for data caching.
//

#include <assert.h>

//=============================================================================
template <typename T>
class Validated {
public:

  Validated();
  // invalid constructor

  Validated(const T& data);
  // valid constructor

  bool valid() const;
  // is this valid or not?

  void invalidate();
  // makes the class invalid again, so call in a function which will change the
  // cached value.

  void set_data(const T& data);
  // set the data.

  operator T();
  // implicit conversion to the template type.

private:

  bool m_valid;
  T m_data;

};

//=============================================================================
//
//D Include the source in the header file as it is a templatised class.
//

//=============================================================================
template <typename T>
Validated<T>::Validated()
//
//D Invalid constructor
//
  : m_valid(false)
{
}

//=============================================================================
template <typename T>
Validated<T>::Validated(const T& data)
//
//D Valid constructor
//
  : m_valid(true),
    m_data(data)
{
}

//=============================================================================
template <typename T>
bool Validated<T>::valid() const
//
//D is this valid or not?
//
{
  return m_valid;
}

//=============================================================================
template <typename T>
void Validated<T>::invalidate()
//
//D Makes the class invalid again, so call when the client calls a function
//D which will change the cached value.
//
{
  m_valid = false;
}

//=============================================================================
template <typename T>
void Validated<T>::set_data(const T& data)
//
//D set the data.
//
{
  m_data = data;
  m_valid = true;
}

//=============================================================================
template <typename T>
Validated<T>::operator T()
//
//D implicit conversion to the template type.
//
{
  // a nice way of returning a message with a standard assert.
  assert(valid() && "Cannot return invalid data.");
  return m_data;
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.