Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #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;
- }
Add Comment
Please, Sign In to add comment