2013-01-21 57 views
1

我有傳遞一個地圖< ...> :: iterator對象到一個函數作爲常量性&上GCC一個問題:傳遞地圖<>:迭代作爲地圖<> ::爲const_iterator&

class MyClass { 


}; 

bool MyClass::_GetInstList(map<string,InstList>::const_iterator & it, const string & sMod) 
{ 
    cout<<"Matched\n"; 
    it = tInstancesData.find(sMod); 
    if(it == tInstancesData.end()) { 
     cout<<"\""<<sMod<<"\" is NOT a module\n"; 
     return false; 
    } 
    return true; 
} 

    bool SomeFunction() 
    { 

      map<string,InstList>::iterator it; 
      if(! _GetInstList(it, SomeString)) return false; 
      it->second.Add(...); // Modifying element pointed by "it" 

    } 

我的問題是,在Visual Studio 2010上面的代碼工作得很好,但是在GCC 4.1.2上,我得到一個錯誤,說沒有與函數調用匹配的函數_GetInstList(它,SomeString)。這個問題似乎是將迭代器轉換爲const_iterator &。

我必須把它作爲參考,因爲它在_GetInstList()內部發生了變化,調用者函數會檢查它。 (「it」指針被改變而不是一個尖銳的元素)。

另外,SomeFunction()中的「it」不能是const,因爲它改變了一個元素。

我怎樣才能解決這個問題?

編輯: 對於那些誰認爲這個問題是從迭代常量性的轉換: 如果函數原型更改爲不採取常量性作爲參考的代碼編譯好,問題是常量&。

+1

轉換調用之前常量性?或者首先從一個const_iterator開始?或者讓代碼通用並接受任何迭代器。 –

+0

爲什麼'_GetInstList()'需要'const_iterator'? – Adam27X

+0

該標準說'iterator'可以轉換爲'const_iterator'。它並沒有說'iterator' *是一個* const_iterator',所以它不適用於引用它。它不會從它的const對應物繼承,所以它是需要轉換的轉換。 – leemes

回答

-2

我想也許這種方法應該重新設計。傳遞迭代器很麻煩,讓其他人閱讀困惑。這樣做有多難?

+2

你認爲傳遞什麼而不是迭代器? –

+0

對象本身?無論哪種方式,我認爲在函數參數中使用迭代器不會提供一個乾淨的,可重用的接口供其他人使用。只是我的觀點。 – Andrew

+0

對象本身不能移動到以下對象。 –

2

將您的參數類型更改爲const map<string,InstList>::const_iterator&或只是map<string,InstList>::const_iterator

下面是一個例子演示與簡單類型的問題(解決方案):

void func1(double& x){} 
void func2(const double& x){} 

int main() 
{ 
    int x; 
    func1(x); // error: 'func1' : cannot convert parameter 1 from 'int' to 'double &' 
    func2(x); // succeeds 
} 
相關問題