Skip to content

Instantly share code, notes, and snippets.

@bbkane
Last active January 30, 2018 04:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbkane/9d7f919ba0a59c1ad4614517c54e8d1e to your computer and use it in GitHub Desktop.
Save bbkane/9d7f919ba0a59c1ad4614517c54e8d1e to your computer and use it in GitHub Desktop.
Slow, fat, and convenient way to print from C++
#include <iostream>
#include <iterator>
#include <array>
#include <string>
// I think this will bloat binary size and be slower,
// but it's for convenient printing, which is worth it :)
// TODO: don't always call by value...
// Of course, I'm mostly passing ints and strings, so it's probably not too
// much more expensive
struct Printer
{
std::string sep_;
std::string end_;
std::ostream* stream_;
Printer(std::string sep=", ",
std::string end="\n",
std::ostream* stream=&std::cout):
sep_(sep), end_(end), stream_(stream)
{
}
void print()
{
*stream_ << this->end_;
}
template<typename Head>
void print(Head head)
{
*stream_ << head << this->end_;
}
template<typename Head, typename... Tail>
void print(Head head, Tail... tail)
{
*stream_ << head << this->sep_;
this->print(tail...);
}
};
// Print std::array / std::vector mostly
struct ListPrinter
{
std::string sep_;
std::string end_;
std::string begin_container_str_;
std::string end_container_str_;
std::ostream* stream_;
ListPrinter(std::string sep=" ",
std::string end="\n",
std::string begin_container_str = "[",
std::string end_container_str = "]",
std::ostream* stream=&std::cout):
sep_(sep), end_(end),
begin_container_str_(begin_container_str),
end_container_str_(end_container_str),
stream_(stream)
{
}
template<typename ListType>
void print(const ListType& listref)
{
const auto last_one_it = std::end(listref) - 1;
*stream_ << begin_container_str_;
for(auto i = std::begin(listref);
i != last_one_it;
++i)
{
*stream_ << *i << this->sep_;
}
*stream_ << *last_one_it;
*stream_ << end_container_str_;
*stream_ << this->end_;
}
};
// Allocate every time, but convenient!
template<typename... Args>
void print(Args&&... args)
{
auto p = Printer();
p.print(std::forward<Args>(args)...);
}
// Allocate every time, but convenient!
template<typename... Args>
void lprint(Args&&... args)
{
auto lp = ListPrinter();
lp.print(std::forward<Args>(args)...);
}
#include <array>
#include "pythonic_print.h"
int main()
{
print("1", 2, 3);
lprint(std::array<int, 3>{{4,5,6}});
auto lp = ListPrinter(",\n ", "\n", "<", ">");
lp.print(std::array<int, 3>{{4,5,6}});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment