diff --git a/Chapter04/01_static_assert/main.cpp b/Chapter04/01_static_assert/main.cpp index 5fa5c8c1..3d69136d 100644 --- a/Chapter04/01_static_assert/main.cpp +++ b/Chapter04/01_static_assert/main.cpp @@ -1,20 +1,35 @@ #include #include +// C++17 has std::byte out of the box! +// Unfortunately this is as C++03 example. +typedef unsigned char byte_t; + template -void serialize_bad(const T& value, boost::array& buffer) { +void serialize_bad(const T& value, boost::array& buffer) { + // TODO: check buffer size. + std::memcpy(&buffer[0], &value, sizeof(value)); +} + +namespace example2 { + +template +void serialize_bad(const T& value, boost::array& buffer) { + // TODO: think of something better. assert(BufSizeV >= sizeof(value)); - // TODO: fixme std::memcpy(&buffer[0], &value, sizeof(value)); } +} // namespace example 2 + + #include -#include +#include template -void serialize(const T& value, boost::array& buffer) { +void serialize(const T& value, boost::array& buffer) { BOOST_STATIC_ASSERT(BufSizeV >= sizeof(value)); - BOOST_STATIC_ASSERT(boost::is_pod::value); + BOOST_STATIC_ASSERT(boost::has_trivial_copy::value); std::memcpy(&buffer[0], &value, sizeof(value)); } @@ -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::type t1_nonconst_t; + + t1_nonconst_t value; + (void)value; } template -void serialize2(const T& value, boost::array& buf) { - BOOST_STATIC_ASSERT_MSG(boost::is_pod::value, +void serialize2(const T& value, boost::array& buf) { + BOOST_STATIC_ASSERT_MSG(boost::has_trivial_copy::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)); @@ -74,6 +92,10 @@ int main() { // Somewhere in code: boost::array buf; + serialize_bad('1', buf); + example2::serialize_bad('1', buf); + serialize('1', buf); + serialize2('2', buf); //serialize2(std::string("Hello word"), buf); (void)buf;