modern_cpp_tutorial/chapters/chapter_02/src/variadic_templates.cpp

36 lines
949 B
C++

#include "variadic_templates.h"
#include <iostream>
template <typename T> void my_recursive_printf(T value) {
std::cout << value << std::endl;
}
template <typename T, typename... Ts>
void my_recursive_printf(T value, Ts... args) {
std::cout << value;
my_recursive_printf(args...);
}
template <typename T, typename... Ts>
void my_expanded_printf(T value, Ts... args) {
std::cout << value;
if constexpr (sizeof...(args) > 0) {
my_expanded_printf(args...);
} else {
std::cout << std::endl;
}
}
template <typename... T> auto sum(T... t) { return (t + ...); }
void VariadicTemplates::run() {
std::cout << "my_recursive_printf(1, 2, \"3\", 4.5, \"hello\"): ";
my_recursive_printf(1, 2, "3", 4.5, "hello");
std::cout << "my_expanded_printf(1, 2, \"3\", 4.5, \"hello\"): ";
my_expanded_printf(1, 2, "3", 4.5, "hello");
std::cout << "sum(1, 2, 3, 4, 5, 6, 7): " << sum(1, 2, 3, 4, 5, 6, 7)
<< std::endl;
}