Created
September 2, 2022 04:23
-
-
Save marler8997/e93fa926bc43522729b2da77913cf1ae to your computer and use it in GitHub Desktop.
c++ unique template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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