【发布时间】:2021-06-29 15:55:13
【问题描述】:
有一个分配器:
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 */
static auto & get_pool( void ) noexcept;
};
它需要为 .cpp 文件中的特定类型定义 get_pool()。 pool_allocator 在内存池中分配实例。
struct cpu { ... };
要定义池本身 - 实例所在的内存区域可能如下所示:
memory_pool<cpu, 4> cpu_storage;
template<>
auto & pool_allocator<cpu>::get_pool( void ) noexcept {
return cpu_storage;
}
在尝试使用时:
class process {
unique_ptr<cpu> m_cpu { nullptr };
};
我面临 GCC 报告的问题:
error: use of 'static auto& ReVolta::pool_allocator<T>::get_pool() [with T = cpu]' before deduction of 'auto'
get_pool().deallocate( ptr, n ); // line of code within the pool_allocator<T>::deallocate(...) implemnetation
我可以请求帮助吗?
【问题讨论】:
-
你的
get_pool( void)函数声明不应该使用auto作为返回类型,你需要明确指定它的返回类型。 -
让
get_pool成为免费功能怎么样? -
@Ranoiaetep 使 get_pool() 免费函数有什么好处?
标签: c++ auto return-type-deduction