没有匹配的成员函数来调用"擦除"

no matching member function for call to 'erase'

本文关键字:调用 函数 擦除 成员      更新时间:2023-10-16

以下是导致错误的代码:

工厂.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
}

我得到的错误是:

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

有什么建议吗?谢谢

这是C++98中map::erase的签名:

void erase( iterator position );

这个函数需要一个iterator,但您传递的是一个const_iterator。这就是代码无法编译的原因。

我该如何解决这个问题?

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

iterator erase( const_iterator position );

如果不能使用新标准,则必须将变量更改为iterator

您正在将const_iterator传递给一个需要普通迭代器的方法。

请参阅:http://www.cplusplus.com/reference/stl/map/erase/

看看大师怎么说:

有效STL中的Scot-Meyers

项目26。与const迭代器、reverse_iterator和const_reverse_iterator相比,更喜欢迭代器。尽管容器支持四种迭代器类型,但其中一种类型具有其他类型所没有的特权。这种类型是迭代器,迭代器是特殊的。

typedef deque<int> IntDeque; //STL container and
typedef lntDeque::iterator Iter; // iterator types are easier
typedef lntDeque::const_iterator ConstIter; // to work with if you
// use some typedefs
Iter i;
ConstIter ci;
… //make i and ci point into
// the same container
if (i == ci ) ... //compare an iterator
// and a const_iterator

第27项。使用distance和advance将容器的const_iterator转换为迭代器

typedef deque<int> IntDeque; //convenience typedefs
typedef lntDeque::iterator Iter;
typedef lntDeque::const_iterator ConstIter;
ConstIter ci; // ci is a const_iterator
…
Iter i(ci); // error! no implicit conversion from
// const_iterator to iterator
Iter i(const_cast<Iter>(ci)); // still an error! can't cast a
// const_iterator to an iterator

有效的是前进和距离

typedef deque<int> IntDeque; //as before
typedef IntDeque::iterator Iter;
typedef IntDeque::const_iterator ConstIter;
IntDeque d;
ConstIter ci;
… // make ci point into d
Iter i(d.begin()); // initialize i to d.begin()
Advance(i, distance(i, ci)) //move i up to where ci is
// (but see below for why this must
// be tweaked before it will compile)