2014-09-04 20 views
-2

我已經試過那些2個功能,以應對雙方char和wchar_t的模板char和wchar_t的沒有給出匹配成員

C++ count matches regex function that works with both char and wchar_t? C++ regex with char and wchar_t?

對於我的char *它工作正常,但是當它來使用wchar_t *它給出了一個沒有匹配的成員函數調用。我不明白爲什麼...

class myClass 
{ 
    int occurrence = 0; 
    string new_String; 

public: 


    template<typename CharType> 
    void replaceSubstring(const CharType* find, const CharType* str, const CharType* rep) { 
     basic_string<CharType> text(str); 
     basic_regex<CharType> reg(find); 

     new_String = regex_replace(text, reg, rep); 



    } 

    template<typename CharT> 
    void countMatches(const CharT* find, const CharT* str) 
     { 
      basic_string<CharT> text(str); 
      basic_regex<CharT> reg(find); 
      typedef typename basic_string<CharT>::iterator iter_t; 
      occurrence = distance(regex_iterator<iter_t>(text.begin(), text.end(), reg), 
          regex_iterator<iter_t>()); 
     } 


    void display() 
    { 
     cout << "occurrence " << occurrence << " new string " << new_String << endl; 
    } 

}; 



int main() 
{ 

    const char *str1 = "NoPE NOPE noPE NoPE NoPE"; 
    const wchar_t *str2 = L"NoPE NOPE noPE NoPE NoPE"; 

    myClass test; 


    test.countMatches("Ni",str1); 
    test.replaceSubstring("No",str1,"NO"); 
    test.display(); 

    test.countMatches("Ni",str2); 
    test.replaceSubstring("No",str2,"No"); 
    test.display(); 




    return 0; 
} 
+1

你能粘貼代碼嗎?已發佈 – 2014-09-04 10:05:29

+0

。正如你所看到的,從其他兩個問題 – UncleSax 2014-09-04 10:10:01

+0

的功能是一樣的,你在哪裏使用'str1'? – 2014-09-04 10:11:57

回答

2

replaceSubstring(),你與basic_regex<ChartType>分配的regex_replace結果爲std::string。這在CharType不是char時失敗,因爲std::string沒有這樣的賦值運算符。

此外,只需要使用寬字符字符串調用寬字符版本,因爲它的參數具有相同的類型。所以:

test.countMatches(L"Ni",str2); 
test.replaceSubstring(L"No",str2,L"No"); 
test.display(); 
+0

但它的錯誤是在兩個replaceSubstring比countMatches調用。 它甚至沒有到達那裏 – UncleSax 2014-09-04 10:14:45

+0

@UncleSax你從來沒有指定錯誤發生的地方,也沒有給出它的全文,所以很難說清楚。但我認爲我知道這個問題,我會將其添加到答案中。 – Angew 2014-09-04 10:18:06

+0

它是在問題中指定的。但你指出了問題!我的錯。謝謝! – UncleSax 2014-09-04 10:21:45