Collection of C++ snippets
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

54 lines
1.4 KiB

14 years ago
#ifndef BINARY_OUTPUT_HPP
#define BINARY_OUTPUT_HPP
#include <ostream>
// static_asserts are not too good...
// Normal
template <typename T>
struct binary {
14 years ago
T thing;
binary(T const t):thing(t) {}
binary(binary const& c):thing(c.thing) {}
14 years ago
};
template <typename T>
binary<T> make_binary(T const t) {
14 years ago
return binary<T>(t);
}
template <typename T>
std::ostream& operator<<(std::ostream& out, binary<T> const& rhs) {
14 years ago
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
// NOTE: it uses references...
14 years ago
template <typename T, size_t N>
struct binary_arr {
T const(& thing)[N];
binary_arr(const T(& t)[N]):thing(t) {}
binary_arr(binary_arr const& c):thing(c.thing) {}
14 years ago
};
template <typename T, size_t N>
binary_arr<T, N> make_binary(const T(& t)[N]) {
14 years ago
static_assert(N>=0, "lijp");
return binary_arr<T, N>(t);
}
template <typename T, size_t N>
std::ostream& operator<<(std::ostream& out, binary_arr<T, N> const& rhs) {
14 years ago
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