fork download
  1. // Copyright 2017 <Biagio Festa>
  2. #include <iostream>
  3. #include <string>
  4. #include <utility>
  5.  
  6. using DateType = int;
  7.  
  8. class DateOrString {
  9. public:
  10. explicit DateOrString(std::string str)
  11. : m_is_a_string(true), m_string(std::move(str)) {}
  12. explicit DateOrString(DateType date) : m_date(std::move(date)) {}
  13.  
  14. const std::string& get_string() const {
  15. if (m_is_a_string == false) {
  16. throw std::runtime_error("It does not keep a string type");
  17. }
  18. return m_string;
  19. }
  20.  
  21. const DateType& get_date() const {
  22. if (m_is_a_string == true) {
  23. throw std::runtime_error("It does not keep a date type");
  24. }
  25. return m_date;
  26. }
  27.  
  28. bool is_string() const noexcept { return m_is_a_string; }
  29.  
  30. private:
  31. bool m_is_a_string = false;
  32. DateType m_date;
  33. std::string m_string;
  34. };
  35.  
  36. DateOrString api_call(const std::string& selector) {
  37. if (selector.empty()) {
  38. return DateOrString{"This is a string"};
  39. }
  40. return DateOrString{DateType{}};
  41. }
  42.  
  43. int main() {
  44. auto r1 = api_call("");
  45. auto r2 = api_call("s");
  46.  
  47. std::cout << r1.get_string() << '\n';
  48. std::cout << r2.get_date() << '\n';
  49.  
  50. return 0;
  51. }
  52.  
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
This is a string
0