From 89a226b3631b18e8572808114a81c9d7ac5bd1e6 Mon Sep 17 00:00:00 2001 From: Yuanjun Ren Date: Wed, 10 Apr 2024 21:08:59 +0800 Subject: [PATCH] add variadic templates inheritance testcases --- .../variadic_class_inheritance_example.cc | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/template/variadic_class_inheritance_example.cc b/template/variadic_class_inheritance_example.cc index 52d9ec4..f97f5ac 100644 --- a/template/variadic_class_inheritance_example.cc +++ b/template/variadic_class_inheritance_example.cc @@ -111,6 +111,77 @@ TEST(variadic_class_inheritance, example2) { oss << "1, 2, 3, 4, 5, 6, \n"; +#ifndef NDEBUG + debug_msg(oss, act_output); +#endif + + EXPECT_EQ(oss.str(), act_output); +} + +namespace { + +template struct overload_set; + +template struct overload_set : public F1 { + overload_set(F1 &&f1) : F1(std::move(f1)) {} + overload_set(const F1 &f1) : F1(f1) {} + using F1::operator(); +}; + +template +struct overload_set : public F1, public overload_set { + overload_set(F1 &&f1, F &&...f) : F1(std::move(f1)), overload_set(std::forward(f)...) {} + overload_set(const F1 &f1, F &&...f) : F1(f1), overload_set(std::forward(f)...) {} + + using F1::operator(); + using overload_set::operator(); +}; + +template auto overload(F &&...f) { + return overload_set(std::forward(f)...); +} + +// In C++17, we can do better, and it gives us a chance to demonstrate an alternative way of using +// a parameter pack that does not need recursion. + +template struct overload_set_17 : public F... { + overload_set_17(F &&...f) : F(std::forward(f))... {} + + using F::operator()...; // C++17 +}; + +// With deduction guide, there's no need to +template auto overload_17(F &&...f) { + return overload_set(std::forward(f)...); +} + +// Deduction guide for this overload_set +template overload_set_17(F &&...) -> overload_set_17; + +void example3() { + int i = 5; + double d = 7.3; + + auto l = overload_set_17{[](int *i) { std::cout << "i = " << *i << std::endl; }, + [](double *d) { std::cout << "d = " << *d << std::endl; }}; + + l(&i); + l(&d); +} + +} // namespace + +TEST(variadic_class_inheritance, example3) { + std::stringstream oss; + testing::internal::CaptureStdout(); + + example3(); + + oss << "i = 5\n" + "d = 7.3\n"; + + auto act_output = testing::internal::GetCapturedStdout(); + #ifndef NDEBUG debug_msg(oss, act_output); #endif