alignment.hh

Go to the documentation of this file.
00001 // $Id: alignment.hh 3629 2005-12-13 13:09:21Z christi $
00002 #ifndef DUNE_ALIGNMENT_HH
00003 #define DUNE_ALIGNMENT_HH
00004 #include<cstddef>
00005 
00006 namespace Dune
00007 {
00008   
00021   template<class T>
00022   struct AlignmentStruct
00023   {
00024     char c;
00025     T t;
00026   };
00027 
00029   template<class T, std::size_t N>
00030   struct AlignmentHelper
00031   {
00032     enum { N2 = sizeof(AlignmentStruct<T>) - sizeof(T) - N };
00033     char padding1[N];
00034     T t;
00035     char padding2[N2];
00036   };
00037 
00038 #define ALIGNMENT_MODULO(a, b)   (a % b == 0 ? \
00039                                      static_cast<std::size_t>(b) : \
00040                                      static_cast<std::size_t>(a % b))
00041 #define ALIGNMENT_MIN(a, b)      (static_cast<std::size_t>(a) <   \
00042                                      static_cast<std::size_t>(b) ? \
00043                                      static_cast<std::size_t>(a) : \
00044                                      static_cast<std::size_t>(b))
00045   template <class T, std::size_t N>
00046   struct AlignmentTester
00047   {
00048     typedef AlignmentStruct<T>        s;
00049     typedef AlignmentHelper<T, N>     h;
00050     typedef AlignmentTester<T, N - 1> next;
00051     enum
00052       {
00053         a1       = ALIGNMENT_MODULO(N        , sizeof(T)),
00054         a2       = ALIGNMENT_MODULO(h::N2    , sizeof(T)),
00055         a3       = ALIGNMENT_MODULO(sizeof(h), sizeof(T)),
00056         a        = sizeof(h) == sizeof(s) ? ALIGNMENT_MIN(a1, a2) : a3,
00057         result   = ALIGNMENT_MIN(a, next::result)
00058       };
00059   };
00060 
00061   template <class T>
00062   struct AlignmentTester<T, 0>
00063   {
00064     enum 
00065       {
00066         result = ALIGNMENT_MODULO(sizeof(AlignmentStruct<T>), sizeof(T))
00067       };
00068   };
00069   
00073   template <class T>
00074   struct AlignmentOf
00075   {
00076     enum
00077       {
00079         value = AlignmentTester<T, sizeof(AlignmentStruct<T>) - sizeof(T) - 1>::result
00080       };
00081   };
00082   
00084 }
00085 #endif

Generated on 12 Dec 2007 with Doxygen (ver 1.5.1)