- memory[meta header]
- std[meta namespace]
- class template[meta id-type]
- cpp11[meta cpp]
namespace std {
template <class T, class Alloc>
struct uses_allocator;
template <class T, class Alloc>
inline constexpr bool uses_allocator_v = uses_allocator<T, Alloc>::value; // C++17 から
}型 T が Alloc 型のアロケータオブジェクトを用いた uses-allocator 構築をする際に、実際にアロケータオブジェクトを使用するかを調べる。
このクラスが true_type から派生する場合、以下のいずれかの構築が可能である:
T(allocator_arg, alloc, args...)のように、第1引数にallocator_arg、第2引数にAlloc型のアロケータオブジェクトallocをとる構築。T(args..., alloc)のように、最後の引数としてAlloc型のアロケータオブジェクトallocをとる構築。
このクラスのデフォルト実装は、型 T が public なメンバ型 allocator_type を持っており、その型が Alloc から変換可能であれば true_type から派生し、そうでなければ false_type から派生する。
型 T が Alloc から変換可能なメンバ型 allocator_type を持っていないが上記いずれかの構築が可能な場合は、true_type から派生した本クラステンプレートの特殊化を提供することで、アロケータを用いた構築をサポートしていることを示すことが可能である。
- 本型トレイツは、主にスコープアロケータモデルを採用するアロケータで使用されることを意図している。
標準ライブラリでは、scoped_allocator_adaptor、polymorphic_allocatorクラステンプレートで使用されている。 - 標準ライブラリで提供されるいくつかの型は本型トレイツの特殊化を提供している。(
tuple、promise、各種コンテナアダプタ等) pairはtupleと同列の機能と考えられるが、uses-allocator 構築をサポートしていない。このため、標準ライブラリで提供されるスコープアロケータモデルを採用したアロケータでは独自にpairの各要素に対して uses-allocator 構築を適用している。
スコープアロケータモデルを採用したアロケータを自作する場合には、同様の対応を行う方が良いだろう。
なお、C++20 でpairに対する特殊対応を含めた uses-allocator 構築サポートのためのユーティリティ関数が追加されたため、以前に比べて容易に uses-allocator 構築への対応が可能となった。
#include <iostream>
#include <memory>
template <class T, class Allocator = std::allocator<T>>
struct X {
T x_;
Allocator alloc_;
public:
using allocator_type = Allocator;
X(std::allocator_arg_t, Allocator alloc, T x)
: alloc_(alloc), x_(x) {}
};
int main()
{
const bool result = std::uses_allocator<X<int>, std::allocator<int>>::value;
static_assert(result, "should be true");
}- std::uses_allocator[color ff0000]
- std::allocator[link allocator.md]
- std::allocator_arg_t[link allocator_arg_t.md]
- C++11
- Clang, C++11 mode: 3.0
- GCC, C++11 mode: 4.6.4
- ICC: ??
- Visual C++: 2012, 2013