kind_switch_test.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. #include "toolchain/base/kind_switch.h"
  5. #include <gtest/gtest.h>
  6. #include <string>
  7. #include <variant>
  8. #include "common/raw_string_ostream.h"
  9. namespace Carbon {
  10. namespace {
  11. TEST(KindSwitch, Variant) {
  12. auto f = [](std::variant<int, float, char> v) -> std::string {
  13. CARBON_KIND_SWITCH(v) {
  14. case CARBON_KIND(int n): {
  15. return llvm::formatv("int = {0}", n);
  16. }
  17. case CARBON_KIND(float f): {
  18. return llvm::formatv("float = {0}", f);
  19. }
  20. case CARBON_KIND(char c): {
  21. return llvm::formatv("char = {0}", c);
  22. }
  23. }
  24. };
  25. EXPECT_EQ(f(int{1}), "int = 1");
  26. EXPECT_EQ(f(float{2}), "float = 2.00");
  27. EXPECT_EQ(f(char{'h'}), "char = h");
  28. }
  29. TEST(KindSwitch, VariantUnusedValue) {
  30. auto f = [](std::variant<int, float> v) -> std::string {
  31. CARBON_KIND_SWITCH(v) {
  32. case CARBON_KIND(int n): {
  33. return llvm::formatv("int = {0}", n);
  34. }
  35. case CARBON_KIND(float _):
  36. // The float value is not used, we see that using `_` works.
  37. return "float";
  38. }
  39. };
  40. EXPECT_EQ(f(int{1}), "int = 1");
  41. EXPECT_EQ(f(float{2}), "float");
  42. }
  43. } // namespace
  44. } // namespace Carbon