Archived
1
Fork 0
This repository has been archived on 2025-04-09. You can view files and clone it, but cannot push or open issues or pull requests.
it-works/binary_output/binary_output.hpp

61 lines
1.5 KiB
C++
Raw Permalink Normal View History

//
// binary_output.hpp
//
// Created by Joshua Moerman on 05/22/11.
// Copyright 2011 Vadovas. All rights reserved.
//
2011-05-22 16:52:37 +02:00
#ifndef BINARY_OUTPUT_HPP
#define BINARY_OUTPUT_HPP
#include <ostream>
// static_asserts are not too good...
// Normal
template <typename T>
2011-05-22 16:57:05 +02:00
struct binary {
2011-05-22 16:52:37 +02:00
T thing;
2011-05-22 16:57:05 +02:00
binary(T const t):thing(t) {}
binary(binary const& c):thing(c.thing) {}
2011-05-22 16:52:37 +02:00
};
template <typename T>
2011-05-22 16:57:05 +02:00
binary<T> make_binary(T const t) {
2011-05-22 16:52:37 +02:00
return binary<T>(t);
}
template <typename T>
2011-05-22 16:57:05 +02:00
std::ostream& operator<<(std::ostream& out, binary<T> const& rhs) {
2011-05-22 16:52:37 +02:00
static_assert(std::is_pod<T>::value, "Please specialise this function if your type is not POD");
static_assert(!std::is_pointer<T>::value, "Writing pointer");
out.write(reinterpret_cast<const char*>(&(rhs.thing)), sizeof(rhs.thing));
return out;
}
// Array
2011-05-22 16:57:05 +02:00
// NOTE: it uses references...
2011-05-22 16:52:37 +02:00
template <typename T, size_t N>
2011-05-22 16:57:05 +02:00
struct binary_arr {
T const(& thing)[N];
binary_arr(const T(& t)[N]):thing(t) {}
binary_arr(binary_arr const& c):thing(c.thing) {}
2011-05-22 16:52:37 +02:00
};
template <typename T, size_t N>
2011-05-22 16:57:05 +02:00
binary_arr<T, N> make_binary(const T(& t)[N]) {
2011-05-22 16:52:37 +02:00
static_assert(N>=0, "lijp");
return binary_arr<T, N>(t);
}
template <typename T, size_t N>
2011-05-22 16:57:05 +02:00
std::ostream& operator<<(std::ostream& out, binary_arr<T, N> const& rhs) {
2011-05-22 16:52:37 +02:00
static_assert(std::is_pod<T>::value, "Please specialise this function if your type is not POD");
static_assert(!std::is_pointer<T>::value, "Writing pointer");
out.write(reinterpret_cast<const char*>(&(rhs.thing)), sizeof(rhs.thing));
return out;
}
#endif // BINARY_OUTPUT_HPP