Skip to content

Instantly share code, notes, and snippets.

@abrhm
Created March 12, 2018 09:37
Show Gist options
  • Save abrhm/96261e6d30ae6ec4061e0b25d8e69e70 to your computer and use it in GitHub Desktop.
Save abrhm/96261e6d30ae6ec4061e0b25d8e69e70 to your computer and use it in GitHub Desktop.
RAII value
#include <iostream>
#include <type_traits>
template<typename T, class Deleter>
class raii_value
{
public:
static_assert(std::is_fundamental<T>::value, "raii_value must hold a fundamental type");
// Must be initialized
raii_value() = delete;
raii_value(const T value)
: m_value(value)
{}
~raii_value()
{
Deleter d;
// Enforce passing reference
T& value_ref = m_value;
d(value_ref);
}
// Implicit cast to type T
operator T&() { return m_value; }
raii_value<T, Deleter>& operator=(const T value)
{
m_value = value;
return *this;
}
private:
T m_value;
};
struct Delete_int
{
void operator()(int& value)
{
std::cout << "deleter run" << std::endl;
value = 0;
std::cout << "deleter done" << std::endl;
}
};
int main() {
raii_value<int, Delete_int> a{5};
std::cout << a << std::endl;
a = 6;
std::cout << a << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment