Skip to content

Commit

Permalink
Chapter04 recipe01 synced
Browse files Browse the repository at this point in the history
  • Loading branch information
apolukhin committed Apr 20, 2017
1 parent 6633593 commit b98bf66
Showing 1 changed file with 31 additions and 9 deletions.
40 changes: 31 additions & 9 deletions Chapter04/01_static_assert/main.cpp
Original file line number Diff line number Diff line change
@@ -1,20 +1,35 @@
#include <cstring>
#include <boost/array.hpp>

// C++17 has std::byte out of the box!
// Unfortunately this is as C++03 example.
typedef unsigned char byte_t;

template <class T, std::size_t BufSizeV>
void serialize_bad(const T& value, boost::array<unsigned char, BufSizeV>& buffer) {
void serialize_bad(const T& value, boost::array<byte_t, BufSizeV>& buffer) {
// TODO: check buffer size.
std::memcpy(&buffer[0], &value, sizeof(value));
}

namespace example2 {

template <class T, std::size_t BufSizeV>
void serialize_bad(const T& value, boost::array<byte_t, BufSizeV>& buffer) {
// TODO: think of something better.
assert(BufSizeV >= sizeof(value));
// TODO: fixme
std::memcpy(&buffer[0], &value, sizeof(value));
}

} // namespace example 2


#include <boost/static_assert.hpp>
#include <boost/type_traits/is_pod.hpp>
#include <boost/type_traits/has_trivial_copy.hpp>

template <class T, std::size_t BufSizeV>
void serialize(const T& value, boost::array<unsigned char, BufSizeV>& buffer) {
void serialize(const T& value, boost::array<byte_t, BufSizeV>& buffer) {
BOOST_STATIC_ASSERT(BufSizeV >= sizeof(value));
BOOST_STATIC_ASSERT(boost::is_pod<T>::value);
BOOST_STATIC_ASSERT(boost::has_trivial_copy<T>::value);

std::memcpy(&buffer[0], &value, sizeof(value));
}
Expand Down Expand Up @@ -51,18 +66,21 @@ void type_traits_examples(T1& /*v1*/, T2& /*v2*/) {
// int const volatile => int volatile
// const int& => const int&
typedef typename boost::remove_const<T1>::type t1_nonconst_t;

t1_nonconst_t value;
(void)value;
}

template <class T, std::size_t BufSizeV>
void serialize2(const T& value, boost::array<unsigned char, BufSizeV>& buf) {
BOOST_STATIC_ASSERT_MSG(boost::is_pod<T>::value,
void serialize2(const T& value, boost::array<byte_t, BufSizeV>& buf) {
BOOST_STATIC_ASSERT_MSG(boost::has_trivial_copy<T>::value,
"This serialize2 function may be used only "
"with POD types."
"with trivially copyable types."
);

BOOST_STATIC_ASSERT_MSG(BufSizeV >= sizeof(value),
"Can not fit value to buffer. "
"Make buffer bigger."
"Make the buffer bigger."
);

std::memcpy(&buf[0], &value, sizeof(value));
Expand All @@ -74,6 +92,10 @@ int main() {

// Somewhere in code:
boost::array<unsigned char, 1> buf;
serialize_bad('1', buf);
example2::serialize_bad('1', buf);
serialize('1', buf);
serialize2('2', buf);
//serialize2(std::string("Hello word"), buf);

(void)buf;
Expand Down

0 comments on commit b98bf66

Please sign in to comment.