|
BDE 4.14.0 Production release
|
Provide a compile-time check for detecting an empty class type.
bsl::is_empty meta-functionThis component defines a meta-function, bsl::is_empty and a template variable bsl::is_empty_v, that represents the result value of the bsl::is_empty meta-function, which may be used to determine whether a type is a class or struct with no non-static data members other than bit-fields of length 0, no virtual member functions, no virtual base classes, and no base class B for which is_empty<B>::value is false. This meta-function conforms to the definition of the C++11 standard is_empty meta-function in section [meta.unary.prop].
An empty class type type is usually stateless and, can be "stored" in a zero-length memory region. (Hypothetically, an empty object can hold state by means a global address-to-state map, but such a design is rare and is discouraged.) When a class inherits from an empty type, the compiler is expected to optimize away the storage requirements of the empty base class. This optimization is known as the "Empty Base Optimization" or "EBO".
Note that the template variable is_empty_v is defined in the C++17 standard as an inline variable. If the current compiler supports the inline variable C++17 compiler feature, bsl::is_empty_v is defined as an inline constexpr bool variable. Otherwise, if the compiler supports the variable templates C++14 compiler feature, bsl::is_empty_v is defined as a non-inline constexpr bool variable. See BSLS_COMPILERFEATURES_SUPPORT_INLINE_VARIABLES and BSLS_COMPILERFEATURES_SUPPORT_VARIABLE_TEMPLATES macros in bsls_compilerfeatures component for details.
In this section we show intended use of this component.
Suppose we wish to create a generic function that will allocate a record comprising a value of specified t_TYPE and a description in the form of a null-terminated character string. First, we declare the function prototype:
Next, we implement the function so that the copy of value takes up no space if t_TYPE is an empty class. We manage this by computing a zero storage requirement if is_empty<t_TYPE>::value is true:
Finally, we use makeRecord with both an empty and non-empty value type: