char和wchart的模板没有提供匹配的成员

template for char and wchar_t gives no matching member

本文关键字:成员 wchart char      更新时间:2023-10-16

为了处理char和wchar_t ,我尝试了这两个函数

C++计数是否匹配同时使用char和wchar_t的regex函数?带有char和wchar_t的C++正则表达式?

对于我的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;
}

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

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

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