char和wchar_t的模板没有给出匹配的成员

时间:2014-09-04 10:04:24

标签: c++ c regex templates

我已经尝试过这两个函数来处理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 个答案:

答案 0 :(得分:2)

replaceSubstring()中,您将regex_replace的结果与basic_regex<ChartType>分配到std::string。当CharType不是char时失败,因为std::string没有这样的赋值运算符。

此外,您需要仅使用宽字符串调用宽字符版本,因为其参数具有相同的类型。所以:

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