Dune Core Modules (2.3.1)

alignment.hh
Go to the documentation of this file.
1 // -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 // vi: set et ts=4 sw=2 sts=2:
3 // $Id$
4 #ifndef DUNE_ALIGNMENT_HH
5 #define DUNE_ALIGNMENT_HH
6 #include <cstddef>
7 #if HAVE_TYPE_TRAITS
8 #include <type_traits>
9 #elif HAVE_TR1_TYPE_TRAITS
10 #include <tr1/type_traits>
11 #endif
12 
13 namespace Dune
14 {
15 
27  namespace
28  {
29 
34  template<class T>
35  struct AlignmentStruct
36  {
37  char c;
38  T t;
39  void hack();
40  };
41 
46  template<class T, std::size_t N>
47  struct AlignmentHelper
48  {
49  enum { N2 = sizeof(AlignmentStruct<T>) - sizeof(T) - N };
50  char padding1[N];
51  T t;
52  char padding2[N2];
53  };
54 
55 #define ALIGNMENT_MODULO(a, b) (a % b == 0 ? \
56  static_cast<std::size_t>(b) : \
57  static_cast<std::size_t>(a % b))
58 #define ALIGNMENT_MIN(a, b) (static_cast<std::size_t>(a) < \
59  static_cast<std::size_t>(b) ? \
60  static_cast<std::size_t>(a) : \
61  static_cast<std::size_t>(b))
63  template <class T, std::size_t N>
64  struct AlignmentTester
65  {
66  typedef AlignmentStruct<T> s;
67  typedef AlignmentHelper<T, N> h;
68  typedef AlignmentTester<T, N - 1> next;
69  enum
70  {
71  a1 = ALIGNMENT_MODULO(N , sizeof(T)),
72  a2 = ALIGNMENT_MODULO(h::N2 , sizeof(T)),
73  a3 = ALIGNMENT_MODULO(sizeof(h), sizeof(T)),
74  a = sizeof(h) == sizeof(s) ? ALIGNMENT_MIN(a1, a2) : a3,
75  result = ALIGNMENT_MIN(a, next::result)
76  };
77  };
78 
80  template <class T>
81  struct AlignmentTester<T, 0>
82  {
83  enum
84  {
85  result = ALIGNMENT_MODULO(sizeof(AlignmentStruct<T>), sizeof(T))
86  };
87  };
88  } //end anonymous namespace
89 
98  template <class T>
99  struct AlignmentOf
100  {
101 
102  enum
103  {
105 #ifdef HAVE_TYPE_TRAITS
106  value = std::alignment_of<T>::value
107 #elif HAVE_TR1_TYPETRAITS
108  value = std::tr1::alignment_of<T>::value
109 #else
110  value = AlignmentTester<T, sizeof(AlignmentStruct<T>) - sizeof(T) -1>::result
111 #endif
112  };
113  };
114 
116 }
117 #endif
Dune namespace.
Definition: alignment.hh:14
Calculates the alignment requirement of a type.
Definition: alignment.hh:100
@ value
The alignment requirement.
Definition: alignment.hh:110
Creative Commons License   |  Legal Statements / Impressum  |  Hosted by TU Dresden  |  generated with Hugo v0.80.0 (May 16, 22:29, 2024)