VariantIdentifier.h 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * VariantIdentifier.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #pragma once
  11. #include "IdentifierBase.h"
  12. VCMI_LIB_NAMESPACE_BEGIN
  13. /// This class represents field that may contain value of multiple different identifier types
  14. template<typename... Types>
  15. class VariantIdentifier
  16. {
  17. using Type = std::variant<Types...>;
  18. Type value;
  19. public:
  20. VariantIdentifier()
  21. {}
  22. template<typename IdentifierType>
  23. VariantIdentifier(const IdentifierType & identifier)
  24. : value(identifier)
  25. {}
  26. int32_t getNum() const
  27. {
  28. int32_t result;
  29. std::visit([&result] (const auto& v) { result = v.getNum(); }, value);
  30. return result;
  31. }
  32. std::string toString() const
  33. {
  34. std::string result;
  35. std::visit([&result] (const auto& v) { result = v.encode(v.getNum()); }, value);
  36. return result;
  37. }
  38. template<typename IdentifierType>
  39. IdentifierType as() const
  40. {
  41. auto * result = std::get_if<IdentifierType>(&value);
  42. assert(result);
  43. if (result)
  44. return *result;
  45. else
  46. return IdentifierType();
  47. }
  48. template <typename Handler> void serialize(Handler &h)
  49. {
  50. h & value;
  51. }
  52. bool operator == (const VariantIdentifier & other) const
  53. {
  54. return value == other.value;
  55. }
  56. bool operator != (const VariantIdentifier & other) const
  57. {
  58. return value != other.value;
  59. }
  60. bool operator < (const VariantIdentifier & other) const
  61. {
  62. return value < other.value;
  63. }
  64. };
  65. VCMI_LIB_NAMESPACE_END