Created
July 30, 2015 19:13
-
-
Save momchil-velikov/94b336ddee12aaccc7a4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <utility> | |
template <typename T> constexpr size_t align_to(size_t n) { | |
return (n + alignof(T) - 1) & -alignof(T); | |
} | |
template <typename T> constexpr size_t skip(size_t n) { | |
return align_to<T>(n) + sizeof(T); | |
} | |
template <typename... T> struct layout_helper; | |
template <> struct layout_helper<> { | |
static constexpr size_t size(size_t n = 0) { return n; } | |
template <size_t N> static constexpr size_t offset(size_t n = 0) { return n; } | |
}; | |
template <typename T, typename... Ts> struct layout_helper<T, Ts...> { | |
static constexpr size_t size(size_t n = 0) { | |
return layout_helper<Ts...>::size(skip<T>(n)); | |
} | |
template <size_t N> static constexpr size_t offset(size_t n = 0) { | |
return N == 0 ? align_to<T>(n) | |
: layout_helper<Ts...>::template offset<N - 1>(skip<T>(n)); | |
} | |
}; | |
int main() { | |
using layout = layout_helper<int, char, char, float>; | |
std::cout << "size: " << layout::size() << std::endl; | |
std::cout << "0: " << layout::offset<0>() << std::endl; | |
std::cout << "1: " << layout::offset<1>() << std::endl; | |
std::cout << "2: " << layout::offset<2>() << std::endl; | |
std::cout << "3: " << layout::offset<3>() << std::endl; | |
std::cout << "4: " << layout::offset<4>() << std::endl; | |
std::cout << "5: " << layout::offset<5>() << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment