variant.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #pragma once
  2. #include <util/generic/string.h>
  3. #include <util/generic/variant.h>
  4. namespace NYT {
  5. ////////////////////////////////////////////////////////////////////////////////
  6. class TStringBuilderBase;
  7. template <class... Ts>
  8. void FormatValue(TStringBuilderBase* builder, const std::variant<Ts...>& variant, TStringBuf spec);
  9. void FormatValue(TStringBuilderBase* builder, const std::monostate&, TStringBuf /*format*/);
  10. template <class... Ts>
  11. TString ToString(const std::variant<Ts...>& variant);
  12. ////////////////////////////////////////////////////////////////////////////////
  13. //! A concise way of creating a functor with an overloaded operator().
  14. /*!
  15. * Very useful for std::visit-ing variants. For example:
  16. *
  17. * std::visit(TOverloaded{
  18. * [] (int i) { printf("The variant holds an int: %d!", i); },
  19. * [] (const std::string& s) { printf("The variant holds a string: '%s'!", s); }
  20. * }, variantVariable);
  21. */
  22. template<class... Ts> struct TOverloaded : Ts... { using Ts::operator()...; };
  23. template<class... Ts> TOverloaded(Ts...) -> TOverloaded<Ts...>;
  24. ////////////////////////////////////////////////////////////////////////////////
  25. //! An alternative to std::visit that takes its variant argument first.
  26. /*!
  27. * This deprives it of being able to visit a Cartesian product of variants but
  28. * in exchange allows to receive multiple visitor functors. All of operator()s
  29. * these functors have are used to visit the variant after a single unified
  30. * overload resolution. For example:
  31. *
  32. * Visit(variantVariable,
  33. * [] (int i) { printf("The variant holds an int: %d!", i); },
  34. * [] (const std::string& s) { printf("The variant holds a string: '%s'!", s); });
  35. */
  36. template <class T, class... U>
  37. auto Visit(T&& variant, U&&... visitorOverloads)
  38. {
  39. return std::visit(TOverloaded{std::forward<U>(visitorOverloads)...}, std::forward<T>(variant));
  40. }
  41. ////////////////////////////////////////////////////////////////////////////////
  42. } // namespace NYT
  43. #define VARIANT_INL_H_
  44. #include "variant-inl.h"
  45. #undef VARIANT_INL_H_