2011-06-02 75 views
2

我正在編譯兩個不同的編譯器下的同一個項目。下面的代碼片段在VS2008編譯罰款,但提供了以下錯誤,當我嘗試使用Eclipse編譯它G正下方++在G ++編譯器錯誤,但不在VS2008,STL模板

G ++錯誤消息:

common.h: In function 'int ci_find_substr(const T&, const T&, const std::locale&)': 
common.h:84: error: expected `;' before 'it' 
common.h:86: error: 'it' was not declared in this scope 

源代碼片斷

#include <stdio.h> 
#include <string.h> 
#include <stdarg.h> 

#include <string> 
#include <algorithm> 
#include <locale> 
#include <iostream> 
#include <algorithm> 

using namespace std ; 

// templated version of my_equal so it could work with both char and wchar_t 
template<typename charT> 
struct my_equal { 
    my_equal(const std::locale& loc) : loc_(loc) {} 
    bool operator()(charT ch1, charT ch2) { 
     return std::toupper(ch1, loc_) == std::toupper(ch2, loc_); 
    } 
private: 
    const std::locale& loc_; 
}; 

// find substring (case insensitive) 
template<typename T> 
int ci_find_substr(const T& str1, const T& str2, const std::locale& loc = std::locale()) 
{ 
    T::const_iterator it = std::search(str1.begin(), str1.end(), 
     str2.begin(), str2.end(), my_equal<T::value_type>(loc)); 
    if (it != str1.end()) return it - str1.begin(); 
    else return -1; // not found 
} 

任何幫助,建議或提示都會有所幫助。 謝謝。

回答

2

嘗試把typename T::const_iterator it = std::search(etc.)我不認爲它是承認T::const_iterator作爲一種類型。

當我試圖編譯代碼以g ++ 4.5.2,它給了我下面的錯誤消息,這證實了這一點

error: need 'typename' before 'T:: const_iterator' because 'T' is a dependent scope 

編輯:您還需要它的my_equal<T::value_type>(loc)。應改爲my_equal<typename T::value_type>(loc)

+0

我嘗試了幾個你的建議的變化,並得到以下錯誤。 [錯誤:引用模板參數的類型成員,使用'typename T :: value_type'] – 2011-06-02 18:00:21

+0

typename T :: const_iterator it = std :: search(str1.begin(),str1.end(), – 2011-06-02 18:01:42

+0

@Steven看到我的編輯 – jonsca 2011-06-02 18:13:20