调用'erase'没有匹配的成员函数

fra*_*ees 8 c++ templates factory

这是导致错误的代码:

Factory.h:

#include <string>
#include <map>

namespace BaseSubsystems
{
    template <class T>
    class CFactory
    {
    protected:
        typedef T (*FunctionPointer)();
        typedef std::pair<std::string,FunctionPointer> TStringFunctionPointerPair;
        typedef std::map<std::string,FunctionPointer> TFunctionPointerMap;
        TFunctionPointerMap _table;
    public:
        CFactory () {}
        virtual ~CFactory();
    }; // class CFactory

    template <class T> 
    inline CFactory<T>::~CFactory()
    {
        TFunctionPointerMap::const_iterator it = _table.begin();
        TFunctionPointerMap::const_iterator it2;

        while( it != _table.end() )
        {
            it2 = it;
            it++;
            _table.erase(it2);
        }

    } // ~CFactory
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误:

error: no matching member function for call to 'erase' [3]
                         _table.erase(it2);
                         ~~~~~~~^~~~~
Run Code Online (Sandbox Code Playgroud)

有小费吗?谢谢.

R. *_*des 7

这是map::eraseC++ 98中的签名:

void erase( iterator position );
Run Code Online (Sandbox Code Playgroud)

这个功能需要一个,iterator但你传递了一个const_iterator.这就是代码无法编译的原因.

我该如何解决?

在C++ 11中,这甚至不是问题,因此不需要修复.那是因为在C++ 11中,该map::erase函数具有以下签名,因此接受a const_iterator.

iterator erase( const_iterator position );
Run Code Online (Sandbox Code Playgroud)

如果您无法使用新标准,则必须更改变量iterator.