1
0

feat: variadic templates

This commit is contained in:
mandlm 2023-11-04 18:20:13 +01:00
parent f3c8cad317
commit db87dfcf1c
Signed by: mandlm
GPG Key ID: 4AA25D647AA54CC7
4 changed files with 50 additions and 1 deletions

View File

@ -7,7 +7,8 @@ add_library(
src/null.cpp src/null.cpp
src/range_based_for.cpp src/range_based_for.cpp
src/structured_binding.cpp src/structured_binding.cpp
src/type_inference.cpp) src/type_inference.cpp
src/variadic_templates.cpp)
target_compile_features(chapter_02 PUBLIC cxx_std_20) target_compile_features(chapter_02 PUBLIC cxx_std_20)

View File

@ -0,0 +1,10 @@
#pragma once
#include "chapter_interface.h"
class VariadicTemplates : public ChapterTest {
virtual void run() override;
virtual const char *name() const override {
return "Variadic templates test";
}
};

View File

@ -0,0 +1,36 @@
#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;
}

View File

@ -11,6 +11,7 @@
#include "range_based_for.h" #include "range_based_for.h"
#include "structured_binding.h" #include "structured_binding.h"
#include "type_inference.h" #include "type_inference.h"
#include "variadic_templates.h"
#include "version.h" #include "version.h"
int main(int argc, char **argv) { int main(int argc, char **argv) {
@ -28,6 +29,7 @@ int main(int argc, char **argv) {
chapter_2_tests.emplace_back(std::make_unique<TypeInferenceTest>()); chapter_2_tests.emplace_back(std::make_unique<TypeInferenceTest>());
chapter_2_tests.emplace_back(std::make_unique<IfConstexprTest>()); chapter_2_tests.emplace_back(std::make_unique<IfConstexprTest>());
chapter_2_tests.emplace_back(std::make_unique<RangeBasedForTest>()); chapter_2_tests.emplace_back(std::make_unique<RangeBasedForTest>());
chapter_2_tests.emplace_back(std::make_unique<VariadicTemplates>());
for (auto &test : chapter_2_tests) { for (auto &test : chapter_2_tests) {
std::cout << "\n" << test->name() << ":" << std::endl; std::cout << "\n" << test->name() << ":" << std::endl;