VariantIdentifier.h 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. if (result)
  43. return *result;
  44. else
  45. return IdentifierType();
  46. }
  47. bool hasValue() const
  48. {
  49. bool result = false;
  50. std::visit([&result] (const auto& v) { result = v.hasValue(); }, value);
  51. return result;
  52. }
  53. template <typename Handler> void serialize(Handler &h)
  54. {
  55. h & value;
  56. }
  57. bool operator == (const VariantIdentifier & other) const
  58. {
  59. return value == other.value;
  60. }
  61. bool operator != (const VariantIdentifier & other) const
  62. {
  63. return value != other.value;
  64. }
  65. bool operator < (const VariantIdentifier & other) const
  66. {
  67. return value < other.value;
  68. }
  69. };
  70. VCMI_LIB_NAMESPACE_END