fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <map>
  4.  
  5. // define some tags to create uniqueness
  6. struct portal_tag {};
  7. struct cake_tag {};
  8.  
  9. // a string-like identifier that is typed on a tag type
  10. template<class Tag, class Base>
  11. struct strong_type
  12. {
  13. // needs to be default-constuctable because of use in map[] below
  14. strong_type(Base s) : _value(std::move(s)) {}
  15. strong_type() : _value() {}
  16.  
  17. // provide access to the underlying string value
  18. const Base& value() const { return _value; }
  19. private:
  20. Base _value;
  21.  
  22. // will only compare against same type of id.
  23. friend bool operator < (const strong_type& l, const strong_type& r) {
  24. return l._value < r._value;
  25. }
  26. };
  27.  
  28.  
  29. // create some type aliases for ease of use
  30. using PortalId = strong_type<portal_tag, std::string>;
  31. using CakeId = strong_type<cake_tag, std::string>;
  32.  
  33. using namespace std;
  34.  
  35. // confirm that requirements are met
  36. auto main() -> int
  37. {
  38. PortalId portal_id("2");
  39. CakeId cake_id("is a lie");
  40. std::map<CakeId, PortalId> p_to_cake; // OK
  41.  
  42. p_to_cake[cake_id] = portal_id; // OK
  43. //p_to_cake[portal_id] = cake_id; // COMPILER ERROR
  44.  
  45. //portal_id = cake_id; // COMPILER ERROR
  46. //portal_id = "1.0"; // COMPILER ERROR
  47. portal_id = PortalId("42"); // OK
  48. return 0;
  49. }
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
Standard output is empty