Created
March 12, 2018 09:37
-
-
Save abrhm/96261e6d30ae6ec4061e0b25d8e69e70 to your computer and use it in GitHub Desktop.
RAII value
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
#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