Cache line padding for variables that are a multiple of cache line size
Taking a page from std::aligned_storage<>
, I've come up with the following:
template<class T, bool = false>struct padded{ using type = struct { alignas(CACHELINE_SIZE)T myObj; char padding[CLPAD(sizeof(T))]; };};template<class T>struct padded<T, true>{ using type = struct { alignas(CACHELINE_SIZE)T myObj; };};template<class T>using padded_t = typename padded<T, (sizeof(T) % CACHELINE_SIZE == 0)>::type;
Usage:
struct alignas(32) my_type_1 { char c[32]; }; // char c[32] to silence MSVC warningstruct my_type_2 { char c[CACHELINE_SIZE * 2]; }; // dittoint main(){ padded_t<my_type_1> pt0; padded_t<my_type_2> pt1; sizeof(pt0); // 128 alignof(pt0); // 128 sizeof(pt1); // 256 alignof(pt1); // 128}
You can provide a function to access myObj
however you wish.