fork download
  1. #include <iostream>
  2. #include <functional>
  3.  
  4. template < typename T >
  5. class my_ {
  6. T value;
  7. std::function<void(T const &)> notifier;
  8. public:
  9. template < typename F >
  10. my_( T const & init, F f )
  11. : value( init ), notifier( f ) { }
  12. // for write
  13. T& operator=( T const & next ) {
  14. if( !std::equal_to<T>()(value, next) )
  15. notifier( next );
  16.  
  17. return value = next;
  18. }
  19. // for read
  20. operator T const & () const
  21. { return value; }
  22. };
  23.  
  24. struct Foo {
  25. Foo( int init )
  26. : value( init,
  27. []( int const & next ) {
  28. std::cout << "\tvalue changed to :" << next << std::endl;
  29.  
  30. } )
  31. { }
  32.  
  33. my_<int> value;
  34. };
  35.  
  36. int main() {
  37.  
  38. Foo foo( 2 );
  39. // write
  40. int new_values[] = { 1, 1, 1, 2, 3, 3 };
  41. size_t const size = sizeof(new_values) / sizeof(*new_values);
  42.  
  43. for( size_t i = 0; i != size; ++i ) {
  44. std::cout << "set in index: " << i << std::endl;
  45. foo.value = new_values[ i ];
  46. }
  47.  
  48. // read
  49. std::cout << "final value: " << foo.value << std::endl;
  50. }
Success #stdin #stdout 0s 3032KB
stdin
Standard input is empty
stdout
set in index: 0
	value changed to :1
set in index: 1
set in index: 2
set in index: 3
	value changed to :2
set in index: 4
	value changed to :3
set in index: 5
final value: 3