c++ - Pointer to class with only static methods
问题描述
Is there a way to obtain a pointer to a class consisting of only static methods? There are no member variables.
I have a vector class using a typename alloc = allocator<T>
as one of the template arguments. the allocator<T>
template class is purely made of static methods. I intend to implement a get_allocator
method which provides access to the methods of a given vectors allocator. E.g. so that this works:
int main() {
custom::vector<int> my_vector(10); // custom int-vector of initial size and capacity 10
// use my_vector's allocator<int> instead of new (don't ask why)
int* my_array = my_vector.get_allocator()->allocate(5);
// ^^ rhs should produce same result as new int[5]. allocator<T>::allocate uses ::operator new.
}
Inside custom::vector
I have this method:
alloc* get_allocator() {
return &alloc
}
This throws MSVC Compiler error 2275: 'alloc': illegal use of this type as an expression
Prefixing typename
to the signature doesn't help.
Allocator class looks like this:
template <typename T>
class allocator : public mem_core::base_allocator<T> {
public:
using value_type = T;
using T_ptr = T*;
using T_ref = T&;
static T_ptr address(T_ref value) noexcept {
return mem_core::addressof<T>(value);
}
static void deallocate(T_ptr const ptr, const size_t& count) {
mem_core::deallocate<T>(ptr, count);
}
static T_ptr allocate(const size_t& amount) {
return mem_core::allocate<T>(amount);
}
private:
allocator() = default;
};
解决方案
您无法获得指向类型(例如&int
)的指针,只能指向类型的对象。所以要么创建一个对象并返回一个指向它的指针,要么直接通过类型使用静态函数:
custom::vector<int>::alloc::allocate(5)
.
推荐阅读
- c - 如何使用 MinGW 编译器在程序开始时调用特定函数?
- hy - Hy中的字典合并
- html - 不知道为什么我的英雄部分的 CSS 背景没有出现
- python - Pandas 经纬度分箱到 100x100 分箱
- javascript - 单击时使用开机复制到剪贴板
- rest - 如何在创建 googlesheet 的 url 中指定密钥文件(key.json)
- .net - ConfuserEx CLI 运行但没有输出结果
- status - PDF 表单提交到 .Net Core Web API,返回结果
- c# - Modbus读写值冲突
- python - 尝试在单个 CPU 内核上运行 tensorflow 的问题