fork download
  1. #include <string>
  2. #include <stdexcept>
  3. #include <iostream>
  4.  
  5. template <class T>
  6. struct ConstrainedText {
  7. std::string m;
  8.  
  9. protected:
  10. ConstrainedText() {}
  11. ~ConstrainedText() {}
  12. public:
  13. bool is_valid() {
  14. return T::is_valid_string(m);
  15. }
  16.  
  17. static T Create(std::string const & s)
  18. {
  19. if (T::is_valid_string(s)) {
  20. T t;
  21. static_cast<ConstrainedText<T>&>(t).m = s;
  22. return t;
  23. }
  24.  
  25. throw std::runtime_error("invalid input!");
  26. }
  27. };
  28.  
  29. struct Angle : public ConstrainedText<Angle> {
  30. static bool is_valid_string( std::string s ) {
  31. return s == "deg" || s=="rad";
  32. }
  33. };
  34.  
  35.  
  36. struct Length : public ConstrainedText<Length> {
  37. static bool is_valid_string( std::string s ) {
  38. return s == "mm" || s == "m" || s == "ft" || s == "in";
  39. }
  40. };
  41.  
  42. int main()
  43. {
  44. auto a = Angle::Create("deg");
  45. auto l = Length::Create("mm");
  46.  
  47. try {
  48. Angle::Create("bimbo");
  49. } catch (std::runtime_error & pEx) {
  50. std::cout << "exception as expected" << std::endl;
  51. }
  52.  
  53. try {
  54. Length::Create("bimbo");
  55. } catch (std::runtime_error & pEx) {
  56. std::cout << "exception as expected" << std::endl;
  57. }
  58. }
Success #stdin #stdout 0s 3020KB
stdin
Standard input is empty
stdout
exception as expected
exception as expected