有一个无状态内存池分配器类:
template<typename T>
class pool_allocator {
public:
using value_type = T;
using pointer = value_type *;
/* Default constructor */
constexpr pool_allocator( void ) noexcept = default;
/* Converting constructor used for rebinding */
template<typename U>
constexpr pool_allocator( const pool_allocator<U> & ) noexcept {}
[[nodiscard]] pointer allocate( size_t n, [[maybe_unused]] const pointer hint = nullptr ) const noexcept {
return get_pool().allocate( n );
}
void deallocate( pointer ptr, size_t n ) const noexcept {
get_pool().deallocate( ptr, n );
}
private:
/* Must be defined in particular .cpp files */
/* POINT OF INTERREST HERE: */
static auto & get_pool( void ) noexcept;
};
背后的逻辑是get_pool()
成员函数的特殊化,它旨在返回定义类型的特定内存池,应在其中分配 T 的实例,例如:
class sample { ... };
在 .cpp 文件中:
memory_pool<sample, 10> sample_storage; // memory pool capable of holding up to 10 instances of 'sample'
最后是 .cpp 文件中的 get_pool() 函数模板的特化:
template<>
auto & pool_allocator<sample>::get_pool( void ) noexcept {
return sample_storage; // return the memory_pool instance defined above
}
问题是这样的模板特化仅在.cpp编译单元中可用,并且阻止auto get_pool()
在其他编译单元中的使用(auto
不能推断占位符的类型,因为get_pool()
函数模板特化的主体不可用)
auto
因此,我想以某种方式摆脱get_pool()
.
我面临的问题主要memory_pool
是分配器本身不知道的大小。无论如何,memory_pool 也是我的实现,所以我可以进行任何需要的采用(例如,进一步using
的声明或其他任何需要)。只是它的骨架:
template<typename T, size_t CAPACITY>
class memory_pool {
public:
using element_type = T;
using pointer = element_type *;
constexpr size_t capacity( void ) noexcept {
return CAPACITY;
}
...
};