alignment.hh
Go to the documentation of this file.00001
00002 #ifndef DUNE_ALIGNMENT_HH
00003 #define DUNE_ALIGNMENT_HH
00004 #include<cstddef>
00005
00006 namespace Dune
00007 {
00008
00020 namespace
00021 {
00022
00027 template<class T>
00028 struct AlignmentStruct
00029 {
00030 char c;
00031 T t;
00032 };
00033
00038 template<class T, std::size_t N>
00039 struct AlignmentHelper
00040 {
00041 enum { N2 = sizeof(AlignmentStruct<T>) - sizeof(T) - N };
00042 char padding1[N];
00043 T t;
00044 char padding2[N2];
00045 };
00046
00047 #define ALIGNMENT_MODULO(a, b) (a % b == 0 ? \
00048 static_cast<std::size_t>(b) : \
00049 static_cast<std::size_t>(a % b))
00050 #define ALIGNMENT_MIN(a, b) (static_cast<std::size_t>(a) < \
00051 static_cast<std::size_t>(b) ? \
00052 static_cast<std::size_t>(a) : \
00053 static_cast<std::size_t>(b))
00054
00055 template <class T, std::size_t N>
00056 struct AlignmentTester
00057 {
00058 typedef AlignmentStruct<T> s;
00059 typedef AlignmentHelper<T, N> h;
00060 typedef AlignmentTester<T, N - 1> next;
00061 enum
00062 {
00063 a1 = ALIGNMENT_MODULO(N , sizeof(T)),
00064 a2 = ALIGNMENT_MODULO(h::N2 , sizeof(T)),
00065 a3 = ALIGNMENT_MODULO(sizeof(h), sizeof(T)),
00066 a = sizeof(h) == sizeof(s) ? ALIGNMENT_MIN(a1, a2) : a3,
00067 result = ALIGNMENT_MIN(a, next::result)
00068 };
00069 };
00070
00072 template <class T>
00073 struct AlignmentTester<T, 0>
00074 {
00075 enum
00076 {
00077 result = ALIGNMENT_MODULO(sizeof(AlignmentStruct<T>), sizeof(T))
00078 };
00079 };
00080 }
00081
00090 template <class T>
00091 struct AlignmentOf
00092 {
00093 enum
00094 {
00096 value = AlignmentTester<T, sizeof(AlignmentStruct<T>) - sizeof(T) - 1>::result
00097 };
00098 };
00099
00101 }
00102 #endif