2012-02-06 86 views
6

這裏沒有匹配的成員函數是導致該錯誤代碼:呼叫爲 '刪除'

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 
} 

和錯誤,我得到:

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

任何提示? 謝謝。

+0

什麼是'it2'的需要? '_table.erase(it ++)'怎麼樣? – iammilind 2012-02-06 03:21:17

回答

7

這裏是map::erase在C++ 98簽名:

void erase(iterator position); 

此功能需要一個iterator但你傳遞一個const_iterator。這就是代碼無法編譯的原因。

How do I fix this?

在C++ 11中,這甚至不是問題,所以它不需要修復。這是因爲在C++ 11中,map::erase函數具有以下簽名,因此接受const_iterator

iterator erase(const_iterator position); 

如果您不能使用新的標準,你必須改變你的變量來代替iterator

+0

謝謝。我正在這個上撕掉我的頭髮。 – ontherocks 2014-02-11 13:19:57

+0

你如何傳遞迭代器?請示例代碼? – JackKalish 2016-05-06 00:35:04

+0

@JackKalish呃....'m.erase(it)'? – 2016-05-06 18:39:05

2

看看主說:

蘇格蘭人邁爾斯在有效的STL

第26項宗教迭代常量迭代,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項使用距離,並提前一個容器的const_iterators轉換爲迭代器。

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)