Skip to content

Instantly share code, notes, and snippets.

@jedwardsol
Created February 10, 2022 18:13
Show Gist options
  • Save jedwardsol/47e66825000c10a0a5f18c38d95abc4a to your computer and use it in GitHub Desktop.
Save jedwardsol/47e66825000c10a0a5f18c38d95abc4a to your computer and use it in GitHub Desktop.
print
#pragma once
#include <iostream>
#include <string_view>
#include <format>
#include <utility>
// 1 : intermediate string
template <typename ...ARGS>
void print(std::string_view format, ARGS &&...args)
{
std::cout << std::format(format,std::forward<ARGS>(args)...);
}
// 2 : straight to cout
template <typename ...ARGS>
void print(std::string_view format, ARGS &&...args)
{
std::ostream_iterator<char> cout(std::cout);
std::format_to(cout,format,std::forward<ARGS>(args)...);
}
// 3 intermediate string, array of references
template <typename ...ARGS>
void print(std::string_view format, ARGS &&...args)
{
auto const &vargs=std::make_format_args(args...);
std::cout << std::vformat(format,vargs);
}
// 4 straight to cout, array of references (closest to fmt::print)
template <typename ...ARGS>
void print(std::string_view format, ARGS &&...args)
{
using iterator = std::ostream_iterator<char>;
using context = std::basic_format_context<iterator, char>;
iterator cout(std::cout);
auto const &vargs=std::make_format_args<context>(args..);
std::vformat_to(cout,format,vargs);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment