Skip to content

Instantly share code, notes, and snippets.

@marler8997
Created September 2, 2022 04:23
Show Gist options
  • Save marler8997/e93fa926bc43522729b2da77913cf1ae to your computer and use it in GitHub Desktop.
Save marler8997/e93fa926bc43522729b2da77913cf1ae to your computer and use it in GitHub Desktop.
c++ unique template
template<typename T, T null_value, void (*release)(T)>
class unique {
public:
// TODO: should we include an empty ctor?
// unique() : m_val(null_value) { }
unique() = delete;
unique(T val) : m_val(val) { }
unique(unique&& source) : m_val(source.m_val) {
source.m_val = null_value;
}
~unique() {
if (m_val != null_value) {
release(m_val);
}
}
unique(const unique&) = delete;
unique & operator=(const unique &) = delete;
T val() const { return m_val; }
private:
T m_val;
};
static inline void unique_close_fd(int fd) { close(fd); }
using unique_fd = unique<int, -1, unique_close_fd>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment