Last active
November 25, 2020 11:09
-
-
Save Bktero/9854cc298454e36ba0429fdf5c5600ec to your computer and use it in GitHub Desktop.
[C++17] Recursive variadic template function with if constexpr to print a list of variables of any types to stdout | Equivalent function with fold expression
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
template<typename First, typename... Rest> | |
void trace(First&& first, Rest&& ... rest) { | |
if constexpr (sizeof...(rest) == 0) { | |
std::cout << std::forward<First>(first) << '\n'; | |
} else { | |
std::cout << std::forward<First>(first) << ' '; | |
trace(std::forward<Rest>(rest)...); | |
} | |
} | |
template<typename... Args> | |
void trace2(Args&& ... args) { | |
std::cerr << "Error: "; | |
((std::cerr << args << ' '), ...) << '\n'; | |
// NOTE: unlike first version, there is an extra comma at the end | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "trace.hpp" | |
struct Foo { | |
int bar = 0; | |
std::string baz = "default"; | |
}; | |
std::ostream& operator<<(std::ostream& ostream, const Foo& foo) { | |
return ostream << "Foo: {bar=" << foo.bar << " baz=" << foo.baz << '}'; | |
} | |
int main() { | |
int i = 42; | |
double d = 89.6; | |
std::string s = "hello, world"; | |
trace(i); | |
trace(d); | |
trace(s); | |
Foo foo{42, "I ❤ C++17"}; | |
trace(foo); | |
trace(s, i); | |
trace(i, d, s); | |
trace(i, foo, i, d, s); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
42 | |
89.6 | |
hello, world | |
Foo: {bar=42 baz=I ❤ C++17} | |
hello, world 42 | |
42 89.6 hello, world | |
42 Foo: {bar=42 baz=I ❤ C++17} 42 89.6 hello, world |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment