Reputation: 41163
I am building an STL list. I made a decorator class (MyList
) that is a list of a special class (ProtectMe
). I want all of the items of the list to be const. So here's what I made:
#include <list>
using namespace std;
class ProtectMe{
private:
int data_;
public:
ProtectMe(int data):data_(data){
}
int data() const{return data_;}
};
class MyList{
private:
//A list of constant pointers to constant ProtectMes.
list<const ProtectMe* const> guts_;
public:
void add(const ProtectMe& data){
guts_.push_front(&data);
}
};
I get the following compile error:
error: ‘const _Tp* __gnu_cxx::new_allocator::address(const _Tp&) const [with _Tp = const ProtectMe* const]’ cannot be overloaded
I'm still scratching my head trying to decode where I went wrong. Why doesn't this code compile? What should I change?
Upvotes: 2
Views: 447
Reputation: 72459
The value_type
of standard containers must be CopyInsertable
(or MoveInsertable
) in order for the push_front
to work. The value type of list<const ProtectMe* const>
is constant, so it's not CopyInsertable
.
† CopyInsertable
means that
allocator_traits<A>::construct(m, p, v);
is well defined where p
is a pointer to value_type
, which by default calls placement new on p and thus requires it to be a non-const pointer.
Upvotes: 2