BDE 4.14.0 Production release
|
Provide a compile-time check for determining allocator types.
bslma::IsStdAllocator
This component defines a meta-function, bslma::IsStdAllocator
and a variable template, bslma::IsStdAllocator_v
, that represents the result value of the bslma::IsStdAllocator
meta-function.
bslma::IsStdAllocator
is used to determine if a type meets the requirements for an allocator, as specified in [container.requirements.general]. Note that there is no is_allocator
trait specified in the C++ standard, even though every C++ implementation has a private equivalent.
In C++03, it is impossible to automatically detect conformance to the allocator requirements, owing to limitations in SFINAE capabilities; even elaborate detection metaprogramming will break if a type has a private allocate
method. Therefore, a portable allocator type, some-alloc, must have bslma::IsStdAllocator<some-alloc>
specified directly. There are two ways to specify this trait:
IsStdAllocator<some-alloc>
to derive from bsl::true_type
in namespace BloombergLP::bslma
.The first option will bypass any automatic-detection metalogic. The second option is preferred because it will be checked for correctness – failing to compile if the allocator is missing a critical member.
In C++11 and later, the bslma::IsStdAllocator
trait is detected automatically: for any type A
having a value_type
and allocate
method that meet the allocator requirements, bslma::IsStdAllocator<A>::value
will be true
. However, to prevent inadvertantly declaring an allocator that is not detected in a C++03 build, using this trait in C++11 or later build will yield a compilation error if it is detected that a type is an allocator does not have IsStdAllocator
explicitly specified. The simplest way to avoid that error is to specify IsStdAllocator
deliberately for every allocator, as described above. Alternatively, defining the BSLMA_ISALLOCATOR_IGNORE_CPP03_COMPATIBILITY
macro will suppress the error in C++11 and later builds, defering to automatic allocator detection.
If C++14 variable templates and constexpr variables are supported, the variable template IsStdAllocator_v
is defined to be the value IsStdAllocator<T>::value
. If C++17 inline variables are supported, it is inline.
This section shows the intended use of this component.
Suppose that we want to assert whether a set of types meet the requirements for allocators.
First, we create a struct type MyAllocator
:
Now, we instantiate the bslma::IsStdAllocator
template for both a type that does not meet the allocator requirements and the defined type MyClass
, that does, asserting the value
static data member of each instantiation.
Note that if the current compiler supports C++14 variable templates then we can re-write the snippet of code above using the bslma::IsStdAllocator_v
variable: