首页 > 解决方案 > 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;
};

标签: c++static-methodsallocator

解决方案


您无法获得指向类型(例如&int)的指针,只能指向类型的对象。所以要么创建一个对象并返回一个指向它的指针,要么直接通过类型使用静态函数:

custom::vector<int>::alloc::allocate(5).


推荐阅读