13.14 Layout Control

Ru-Brd

A fairly common template programming challenge is to declare an array of bytes that will be sufficiently large (but not excessively so) to hold an object of an as yet unknown type T ”in other words, a template parameter. One application of this is the so-called discriminated unions (also called variant types or tagged unions ):

 template <... list>  class D_Union {    public:      enum { n_bytes; };      char bytes[n_bytes];  // will eventually hold one of various types   // described by the template arguments    }; 

The constant n_bytes cannot always be set to sizeof(T) because T may have more strict alignment requirements than the bytes buffer. Various heuristics exist to take this alignment into account, but they are often complicated or make somewhat arbitrary assumptions.

For such an application, what is really desired is the ability to express the alignment requirement of a type as a constant expression and, conversely, the ability to impose an alignment on a type, a field, or a variable. Many C and C++ compilers already support an __alignof__ operator, which returns the alignment of a given type or expression. This is almost identical to the sizeof operator except that the alignment is returned instead of the size of the given type. Many compilers also provide #pragma directives or similar devices to set the alignment of an entity. A possible approach may be to introduce an alignof keyword that can be used both in expressions (to obtain the alignment) and in declarations (to set the alignment).

 template <typename T>  class Alignment {    public:      enum { max = alignof(T) };  };  template <... list>  class Alignment {    public:      enum { max = alignof(list[0]) > Alignment<list[1 ...]>::max                    ? alignof(list[0])                    : Alignment<list[1 ...]>::max; }  };  // a set of  Size  templates could similarly be designed   // to determine the largest size among a given list of types  template <... list>  class Variant {    public:      char buffer[Size<list>::max] alignof(Alignment<list>::max);   }; 
Ru-Brd


C++ Templates
C++ Templates: The Complete Guide
ISBN: 0201734842
EAN: 2147483647
Year: 2002
Pages: 185

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net