Created
July 14, 2015 10:28
-
-
Save ilebedie/f006674098a1adaab731 to your computer and use it in GitHub Desktop.
Python-like print in c++
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> | |
using namespace std; | |
void print(){cout<<'\n';} | |
template<typename T, typename ...TAIL> | |
void print(const T &t, TAIL... tail) | |
{ | |
cout<<t<<' '; | |
print(tail...); | |
} |
This is a good solution, but the print function, due to recursion and during compilation, can create a lot of work for the compiler.
// Example for call print(int, string, string, int):
void print(const int&, const string&, const string&, const int&);
void print(const string&, const string&, const int&);
void print(const string&, const int&);
void print(const int&);
You can use fold expressions.
The fold expressions allows you to process a package with parameters without resorting to recursion.
namespace detail {
template <typename T, typename... Tail>
void print_impl(const T& t, const Tail&... tail) {
using namespace std::literals;
std::cout << t;
(..., (std::cout << " "sv << tail));
}
} // namespace detail
template <typename... Tail>
void print(const Tail&... tail) {
if constexpr (sizeof...(tail) != 0) {
detail::print_impl(tail...);
}
std::cout << std::endl;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
genius!