diff --git a/include/llvm/ADT/TypeSwitch.h b/include/llvm/ADT/TypeSwitch.h index bfcb2064301..815b9a40afa 100644 --- a/include/llvm/ADT/TypeSwitch.h +++ b/include/llvm/ADT/TypeSwitch.h @@ -124,6 +124,12 @@ public: return std::move(*result); return defaultFn(this->value); } + /// As a default, return the given value. + LLVM_NODISCARD ResultT Default(ResultT defaultResult) { + if (result) + return std::move(*result); + return defaultResult; + } LLVM_NODISCARD operator ResultT() { diff --git a/unittests/ADT/TypeSwitchTest.cpp b/unittests/ADT/TypeSwitchTest.cpp index fde423d011b..442ac1910a0 100644 --- a/unittests/ADT/TypeSwitchTest.cpp +++ b/unittests/ADT/TypeSwitchTest.cpp @@ -47,7 +47,7 @@ TEST(TypeSwitchTest, CasesResult) { return TypeSwitch(&value) .Case([](auto *) { return 0; }) .Case([](DerivedC *) { return 1; }) - .Default([](Base *) { return -1; }); + .Default(-1); }; EXPECT_EQ(0, translate(DerivedA())); EXPECT_EQ(0, translate(DerivedB()));