Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Type traits

Use case

Compile-time checks for safe binary I/O.

Explanation

Type traits query type properties at compile-time. is_trivially_copyable checks if a type is safe for memcpy (POD/Plain Old Data structs are but classes with std::string are not). static_assert can be used to catch mistakes before runtime.

Code

#include <cstdint>
#include <iostream>
#include <type_traits>

// https://en.wikipedia.org/wiki/Mach-O
struct MachHeader {
  uint32_t magic;
  uint32_t cputype;
};

class Symbol {
  std::string name;

public:
  Symbol(const std::string &n) : name(n) {}
};

int main() {
  std::cout << "MachHeader trivially copyable: " << std::boolalpha
            << std::is_trivially_copyable<MachHeader>::value << "\n";
  std::cout << "Symbol trivially copyable: " << std::boolalpha
            << std::is_trivially_copyable<Symbol>::value << "\n";

  static_assert(std::is_trivially_copyable<MachHeader>::value,
                "MachHeader must be safe for memcpy.");
  return 0;
}

View on GitHub.

Output

$ ./src/c++11/build/type-traits
MachHeader trivially copyable: true
Symbol trivially copyable: false