Guest User

Untitled

a guest
Mar 20th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. #include <iostream>
  2. #include <type_traits>
  3.  
  4.  
  5. template<typename T, class Deleter>
  6. class raii_value
  7. {
  8. public:
  9. static_assert(std::is_fundamental<T>::value, "raii_value must hold a fundamental type");
  10.  
  11. // Must be initialized
  12. raii_value() = delete;
  13.  
  14. raii_value(const T value)
  15. : m_value(value)
  16. {}
  17.  
  18. ~raii_value()
  19. {
  20. Deleter d;
  21. // Enforce passing reference
  22. T& value_ref = m_value;
  23. d(value_ref);
  24. }
  25.  
  26. // Implicit cast to type T
  27. operator T&() { return m_value; }
  28.  
  29. raii_value<T, Deleter>& operator=(const T value)
  30. {
  31. m_value = value;
  32. return *this;
  33. }
  34.  
  35. private:
  36. T m_value;
  37. };
  38.  
  39. struct Delete_int
  40. {
  41. void operator()(int& value)
  42. {
  43. std::cout << "deleter run" << std::endl;
  44. value = 0;
  45. std::cout << "deleter done" << std::endl;
  46. }
  47. };
  48.  
  49.  
  50. int main() {
  51. raii_value<int, Delete_int> a{5};
  52. std::cout << a << std::endl;
  53. a = 6;
  54. std::cout << a << std::endl;
  55. }
Add Comment
Please, Sign In to add comment