fork download
  1. #include <exception>
  2. #include <stdexcept>
  3.  
  4. template <class T, T lower, T upper>
  5. class bounded {
  6. T val;
  7. public:
  8. bounded(bounded const &o) : val(o.val) {}
  9.  
  10. bounded &operator=(T v) {
  11. if ( lower < v && v < upper)
  12. val = v;
  13. else
  14. throw(std::range_error("Value out of range"));
  15. return *this;
  16. }
  17.  
  18. bounded(T const &v=T()) {
  19. if ( lower <= v && v < upper)
  20. val = v;
  21. else
  22. throw(std::range_error("Value out of range"));
  23. val = v;
  24. }
  25. operator T() { return val; }
  26. };
  27.  
  28. //#ifdef TEST
  29. #include <iostream>
  30.  
  31. int main() {
  32. bounded<int, 0, 512> x;
  33.  
  34. try {
  35. x = 256;
  36. std::cout << x << std::endl;
  37.  
  38. x = 1024;
  39. std::cout << x << std::endl;
  40. }
  41. catch(std::exception &e) {
  42. std::cerr << "Error: " << e.what() << std::endl;
  43. }
  44. return 0;
  45. }
  46.  
  47. // #endif
  48.  
Success #stdin #stdout 0.01s 2816KB
stdin
Standard input is empty
stdout
256