|
BDE 4.14.0 Production release
|
Provide a meta-function mapping an ALIGNMENT to a primitive type.
ALIGNMENT to a so-aligned primitive typeThis component provides a meta-function, bsls::AlignmentToType, parameterized on an integral ALIGNMENT, that declares a typedef (Type), which is an alias for a primitive type having the indicated ALIGNMENT requirement.
Consider a parameterized type, my_AlignedBuffer, that provides aligned memory to store a user-defined type. A my_AlignedBuffer object is useful in situations where efficient (e.g., stack-based) storage is required.
The my_AlignedBuffer union (defined below) takes a TYPE and the ALIGNMENT requirements for that type as template parameters, and provides an appropriately sized and aligned block of memory via the buffer functions. Note that my_AlignedBuffer ensures that the returned memory is aligned correctly for the specified size by using bsls::AlignmentToType<ALIGNMENT>::Type, which provides a primitive type having the ALIGNMENT requirement. The class definition of my_AlignedBuffer is as follows:
The function definitions of my_AlignedBuffer are as follows:
my_AlignedBuffer can be used to construct buffers for different types and with varied alignment requirements. Consider that we want to construct an object that stores the response of a floating-point operation. If the operation is successful, then the response object stores a double result; otherwise, it stores an error string of type string, which is based on the standard type string (see bslstl_string ). For the sake of brevity, the implementation of string is not explored here. Here is the definition for the Response class:
To create a my_AlignedBuffer object we must specify the alignment value for our types. For simplicity, we use a maximum alignment value for all types (assumed to be 8 here):
Note that we use my_AlignedBuffer to allocate sufficient, aligned memory to store the result of the operation or an error message:
The isError flag indicates whether the response object stores valid data or an error message:
Below we provide a simple public interface suitable for illustration only:
The manipulator functions allow clients to update the response object to store either a double result or an error message:
The isError function informs clients whether a response object stores a result value or an error message:
Below we provide the function definitions. Note that we use the my_AlignedBuffer::buffer function to access correctly aligned memory. Also note that my_AlignedBuffer just provides the memory for an object; therefore, the Response class is responsible for the construction and destruction of the specified objects. Since our Response class is for illustration purposes only, we ignore exception-safety concerns; nor do we supply an allocator to the string constructor, allowing the default allocator to be used instead:
Clients of the Response class can use it as follows: