Skip to content

Commit

Permalink
add variadic templates inheritance testcases
Browse files Browse the repository at this point in the history
  • Loading branch information
wtffqbpl committed Apr 10, 2024
1 parent a8dfe53 commit 89a226b
Showing 1 changed file with 71 additions and 0 deletions.
71 changes: 71 additions & 0 deletions template/variadic_class_inheritance_example.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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 <typename... F> struct overload_set;

template <typename F1> struct overload_set<F1> : public F1 {
overload_set(F1 &&f1) : F1(std::move(f1)) {}
overload_set(const F1 &f1) : F1(f1) {}
using F1::operator();
};

template <typename F1, typename... F>
struct overload_set<F1, F...> : public F1, public overload_set<F...> {
overload_set(F1 &&f1, F &&...f) : F1(std::move(f1)), overload_set<F...>(std::forward<F>(f)...) {}
overload_set(const F1 &f1, F &&...f) : F1(f1), overload_set<F...>(std::forward<F>(f)...) {}

using F1::operator();
using overload_set<F...>::operator();
};

template <typename... F> auto overload(F &&...f) {
return overload_set<F...>(std::forward<F>(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 <typename... F> struct overload_set_17 : public F... {
overload_set_17(F &&...f) : F(std::forward<F>(f))... {}

using F::operator()...; // C++17
};

// With deduction guide, there's no need to
template <typename... F> auto overload_17(F &&...f) {
return overload_set<F...>(std::forward<F>(f)...);
}

// Deduction guide for this overload_set
template <typename... F> overload_set_17(F &&...) -> overload_set_17<F...>;

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
Expand Down

0 comments on commit 89a226b

Please sign in to comment.