Source

Mutable / Mutable / Validated.h

Full commit
//=============================================================================
//
//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;
}