fork download
  1. #include <cstring>
  2. #include <iostream>
  3. #include <type_traits>
  4.  
  5. // TODO: static_assert to detect alignment errors.
  6.  
  7. template<typename T, typename U>
  8. struct binary_concat_t {
  9. enum { total_size = sizeof(T) + sizeof(U) };
  10.  
  11. binary_concat_t(const T & t, const U & u) : t(t), u(u) {}
  12.  
  13. const char * data() const { return reinterpret_cast<const char*>(this); }
  14.  
  15. T t;
  16. U u;
  17. };
  18.  
  19. template<typename T, typename U>
  20. binary_concat_t<T, U> binary_concat(const T & t, const U & u) {
  21. static_assert(std::is_pod<binary_concat_t<T, U>>::value, "Type must be POD!");
  22. return binary_concat_t<T, U>(t, u);
  23. }
  24.  
  25. template<typename T, typename U, typename V>
  26. binary_concat_t<binary_concat_t<T, U>, V> binary_concat(const T & t, const U & u, const V & v) {
  27. return binary_concat(binary_concat(t, u), v);
  28. }
  29.  
  30. struct IPv4Header {
  31. char data[17];
  32. };
  33.  
  34. struct TCPHeader {
  35. char data[20];
  36. };
  37.  
  38. struct HTTPHeader {
  39. char data[23];
  40. };
  41.  
  42. int main() {
  43. IPv4Header ipv4;
  44. TCPHeader tcp;
  45. HTTPHeader http;
  46. auto data = binary_concat(ipv4, tcp, http);
  47.  
  48. std::cout << "sizeof(IPv4Header) = " << sizeof(IPv4Header) << std::endl;
  49. std::cout << "sizeof(TCPHeader) = " << sizeof(TCPHeader) << std::endl;
  50. std::cout << "sizeof(HTTPHeader) = " << sizeof(HTTPHeader) << std::endl;
  51. std::cout << "sizeof(data) = " << sizeof(data) << std::endl;
  52. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In function 'binary_concat_t<T, U> binary_concat(const T&, const U&) [with T = IPv4Header, U = TCPHeader]':
prog.cpp:27:48:   instantiated from 'binary_concat_t<binary_concat_t<T, U>, V> binary_concat(const T&, const U&, const V&) [with T = IPv4Header, U = TCPHeader, V = HTTPHeader]'
prog.cpp:46:46:   instantiated from here
prog.cpp:21:5: error: static assertion failed: "Type must be POD!"
prog.cpp: In function 'binary_concat_t<T, U> binary_concat(const T&, const U&) [with T = binary_concat_t<IPv4Header, TCPHeader>, U = HTTPHeader]':
prog.cpp:27:48:   instantiated from 'binary_concat_t<binary_concat_t<T, U>, V> binary_concat(const T&, const U&, const V&) [with T = IPv4Header, U = TCPHeader, V = HTTPHeader]'
prog.cpp:46:46:   instantiated from here
prog.cpp:21:5: error: static assertion failed: "Type must be POD!"
stdout
Standard output is empty