Q:

Compiler error modifiying member variable in a const function of a template container

template <template <class, class> class ContainerType>
class Movie {
public:
    typedef ContainerType<Actor*, std::allocator<Actor*>> Container;

    bool removeActor(int id) const {
        const Actor* factor = findActor(id);
        typename Container::const_iterator it;
        if (factor == 0) {
            return 0;
        }
        it = std::find_if(actors.begin(), actors.end(), removeActor2(id));
        **actors.erase(it);
        **delete factor;
        return 1;
    }

private:
    std::string _title;
    std::string _director;
    std::string _genre;
    int _rating;
    Container actors;
};

class removeActor2 {
public:
    removeActor2(int id) : _id(id) {}
    const Actor* operator()(Actor* act) {
        if (act->getId() == _id) {
            return act;
        }
        return 0;
    }

private:
    int _id;
};

errors are:
||=== Build: Debug in hw2 (compiler: GNU GCC Compiler) ===|
In instantiation of 'bool summer2014::Movie<ContainerType>::removeActor(int) const [with ContainerType = std::list]':|
|error: no matching function for call to 'std::list<summer2014::Actor*, std::allocator<summer2014::Actor*> >::erase(std::list<summer2014::Actor*, std::allocator<summer2014::Actor*> >::const_iterator&) const'|
 candidates are:|
|108|note: std::list<_Tp, _Alloc>::iterator std::list<_Tp, _Alloc>::erase(std::list<_Tp, _Alloc>::iterator) [with _Tp = summer2014::Actor*; _Alloc = std::allocator<summer2014::Actor*>; std::list<_Tp, _Alloc>::iterator = std::_List_iterator<summer2014::Actor*>]|
|108|note:   no known conversion for argument 1 from 'std::list<summer2014::Actor*, std::allocator<summer2014::Actor*> >::const_iterator {aka std::_List_const_iterator<summer2014::Actor*>}' to 'std::list<summer2014::Actor*, std::allocator<summer2014::Actor*> >::iterator {aka std::_List_iterator<summer2014::Actor*>}'|
note: std::list<_Tp, _Alloc>::iterator std::list<_Tp, _Alloc>::erase(std::list<_Tp, _Alloc>::iterator, std::list<_Tp, _Alloc>::iterator) [with _Tp = summer2014::Actor*; _Alloc = std::allocator<summer2014::Actor*>; std::list<_Tp, _Alloc>::iterator = std::_List_iterator<summer2014::Actor*>]|
|1193|note:   candidate expects 2 arguments, 1 provided|

A:

You are trying to modify a member in a const member. That won't work. Either make removeActor() non-const or declare actors as mutable. Probably the former.

