Skip to content

Instantly share code, notes, and snippets.

@JaiganeshKumaran
Created July 30, 2022 01:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JaiganeshKumaran/8327c75bff69993e902985549cd67ef7 to your computer and use it in GitHub Desktop.
Save JaiganeshKumaran/8327c75bff69993e902985549cd67ef7 to your computer and use it in GitHub Desktop.
Base class to conveniently implement the IClosable interface
#prgama once
#include <winerror.h>
#include <winrt/Windows.Foundation.h>
/// <summary>
/// Provides a base class to conveniently implement the IClosable interface.
/// </summary>
/// <remarks>Your derived class must provide a public or protected Dispose method which will be called by Close when the object hasn't been closed yet.</remarks>
template <typename Derived>
struct Disposable
{
public:
void Close() noexcept
{
if (!m_IsDisposed)
{
static_cast<Derived*>(this)->Dispose();
m_IsDisposed = true;
}
}
~Disposable()
{
Close();
}
protected:
bool m_IsDisposed;
inline void ThrowIfDisposed() const
{
if (m_IsDisposed) throw hresult_error(RO_E_CLOSED);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment