Skip to content

Instantly share code, notes, and snippets.

Created May 15, 2013 10:07
Show Gist options
  • Save anonymous/70fea5e9bf5828e25e8c to your computer and use it in GitHub Desktop.
Save anonymous/70fea5e9bf5828e25e8c to your computer and use it in GitHub Desktop.
template <typename T>
class print_binary_helper
{
public:
static_assert(std::is_integral<T>::value,
"Cannot print non-integer in binary.");
//template <typename U>
friend print_binary_helper<T> print_binary(T value);
// <typename U>
friend std::ostream& operator<<(std::ostream& sink,
const print_binary_helper<T> source);
//template <typename U>
friend std::wostream& operator<<(std::wostream& sink,
const print_binary_helper<T> source);
private:
explicit print_binary_helper(T value) :
mValue(value)
{}
template <typename Sink, typename Char>
Sink& do_print(Sink& sink, Char on, Char off) const
{
for (auto mask = T(1) << (std::numeric_limits<T>::digits - 1);
mask != 0; mask >>= 1)
{
const auto isOn = (mValue & mask) != 0;
sink << (isOn ? on : off);
}
return sink;
}
T mValue;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment