VariantIdentifier.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. std::variant<Types...> value;
  18. public:
  19. VariantIdentifier()
  20. {}
  21. template<typename IdentifierType>
  22. VariantIdentifier(const IdentifierType & identifier)
  23. : value(identifier)
  24. {}
  25. int32_t getNum() const
  26. {
  27. int32_t result;
  28. std::visit([&result] (const auto& v) { result = v.getNum(); }, value);
  29. return result;
  30. }
  31. std::string toString() const
  32. {
  33. std::string result;
  34. std::visit([&result] (const auto& v) { result = v.encode(v.getNum()); }, value);
  35. return result;
  36. }
  37. template<typename IdentifierType>
  38. IdentifierType as() const
  39. {
  40. auto * result = std::get_if<IdentifierType>(&value);
  41. assert(result);
  42. if (result)
  43. return *result;
  44. else
  45. return IdentifierType();
  46. }
  47. template <typename Handler> void serialize(Handler &h, const int version)
  48. {
  49. h & value;
  50. }
  51. bool operator == (const VariantIdentifier & other) const
  52. {
  53. return value == other.value;
  54. }
  55. bool operator != (const VariantIdentifier & other) const
  56. {
  57. return value != other.value;
  58. }
  59. bool operator < (const VariantIdentifier & other) const
  60. {
  61. return value < other.value;
  62. }
  63. };
  64. VCMI_LIB_NAMESPACE_END