variant_helpers.h 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef CARBON_COMMON_VARIANT_HELPERS_H_
  5. #define CARBON_COMMON_VARIANT_HELPERS_H_
  6. #include <variant>
  7. #include "common/error.h"
  8. #include "llvm/ADT/StringRef.h"
  9. namespace Carbon {
  10. namespace Internal {
  11. // Form an overload set from a list of functions. For example:
  12. //
  13. // ```
  14. // auto overloaded = Overload{[] (int) {}, [] (float) {}};
  15. // ```
  16. template <typename... Fs>
  17. struct Overload : Fs... {
  18. using Fs::operator()...;
  19. };
  20. template <typename... Fs>
  21. Overload(Fs...) -> Overload<Fs...>;
  22. } // namespace Internal
  23. // Pattern-match against the type of the value stored in the variant `V`. Each
  24. // element of `fs` should be a function that takes one or more of the variant
  25. // values in `V`.
  26. template <typename V, typename... Fs>
  27. auto VariantMatch(V&& v, Fs&&... fs) -> decltype(auto) {
  28. return std::visit(Internal::Overload{std::forward<Fs&&>(fs)...},
  29. std::forward<V&&>(v));
  30. }
  31. } // namespace Carbon
  32. #endif // CARBON_COMMON_VARIANT_HELPERS_H_