Skip to content

Instantly share code, notes, and snippets.

@ilebedie
Created July 14, 2015 10:28
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save ilebedie/f006674098a1adaab731 to your computer and use it in GitHub Desktop.
Save ilebedie/f006674098a1adaab731 to your computer and use it in GitHub Desktop.
Python-like print in c++
#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...);
}
@silvertakana
Copy link

genius!

@NTG-TPL
Copy link

NTG-TPL commented Jul 11, 2023

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