mirror of
https://github.com/changkun/modern-cpp-tutorial.git
synced 2025-12-17 04:34:40 +03:00
see #2: add std::initializer_list for printf back
This commit is contained in:
@@ -17,7 +17,7 @@ void magic(Ts... args) {
|
||||
}
|
||||
|
||||
|
||||
// 1 recursive parameter unpack
|
||||
// 1. recursive parameter unpack
|
||||
template<typename T0>
|
||||
void printf1(T0 value) {
|
||||
std::cout << value << std::endl;
|
||||
@@ -28,13 +28,22 @@ void printf1(T value, Ts... args) {
|
||||
printf1(args...);
|
||||
}
|
||||
|
||||
// 2 variadic template parameter unfold
|
||||
// 2. variadic template parameter unfold
|
||||
template<typename T0, typename... T>
|
||||
void printf2(T0 t0, T... t) {
|
||||
std::cout << t0 << std::endl;
|
||||
if constexpr (sizeof...(t) > 0) printf2(t...);
|
||||
}
|
||||
|
||||
// 3. parameter unpack using initializer_list
|
||||
template<typename T, typename... Ts>
|
||||
auto printf3(T value, Ts... args) {
|
||||
std::cout << value << std::endl;
|
||||
(void) std::initializer_list<T>{([&args] {
|
||||
std::cout << args << std::endl;
|
||||
}(), value)...};
|
||||
}
|
||||
|
||||
int main() {
|
||||
magic();
|
||||
magic(1);
|
||||
@@ -42,5 +51,6 @@ int main() {
|
||||
|
||||
printf1(1, 2, "123", 1.1);
|
||||
printf2(1, 2.3, "abc");
|
||||
printf3(111, 123, "alpha", 1.2);
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user