Trivial container with dispenser information?

I study / play with dispensers, trying to understand how this works. But I'm having problems trying to implement a trivial container that accepts a dispenser. At the moment, I am done with this:

template<class T, class Allocator =std::allocator<T>> class Container {
public:
    using allocator_type    = Allocator;
    using value_type        = T;
    using pointer           = typename std::allocator_traits<allocator_type>::pointer;
    using reference         = value_type&;
    using size_type         = std::size_t;

    Container( size_type n =0 , const allocator_type& allocator =allocator_type() ){
        std::cout << "ctor" << std::endl;
        allocator.allocate(n);
    };
};

int main(int argc, const char* argv[]){
    Container<int> c {5};
    return 0;
}

It gives me an error member function 'allocate' not viable: 'this' argument has type 'const allocator_type' (aka 'const std::__1::allocator<int>'), but function is not marked const

How to fix this error, please? Am I missing something? I intend to use the traits later, but would like it to work using the old way.

+4
source share
1 answer

Your line

allocator.allocate(n);

tries to call a method allocate allocatorthat is not defined as a method const. However, if you look, the type allocatoris equal const allocator_type&, that is, a constant reference to allocator_type.

? , const ( ), , . , , :

allocator_type(allocator).allocate(n);

SergeyA , ad-hoc allocator_type, :

    allocator_type m_alloc; // Should probably be private

    Container( size_type n =0 , const allocator_type& allocator =allocator_type() ) : 
            m_alloc{allocator}{
        std::cout << "ctor" << std::endl;
        m_alloc.allocate(n);
    };
+1

Source: https://habr.com/ru/post/1653933/


All Articles