2
0

get_ref.cpp 573 B

123456789101112131415161718192021222324252627
  1. #include <iostream>
  2. #include <nlohmann/json.hpp>
  3. using json = nlohmann::json;
  4. int main()
  5. {
  6. // create a JSON number
  7. json value = 17;
  8. // explicitly getting references
  9. auto r1 = value.get_ref<const json::number_integer_t&>();
  10. auto r2 = value.get_ref<json::number_integer_t&>();
  11. // print the values
  12. std::cout << r1 << ' ' << r2 << '\n';
  13. // incompatible type throws exception
  14. try
  15. {
  16. auto r3 = value.get_ref<json::number_float_t&>();
  17. }
  18. catch (json::type_error& ex)
  19. {
  20. std::cout << ex.what() << '\n';
  21. }
  22. }