模板字符/wchar_t,字符串/w字符串,cout/wcout,regexp / wregex(或任何可能的解决方法)

template char/wchar_t, string/wstring, cout/wcout, regexp/wregex (or any possible workaround)

本文关键字:字符串 任何可 方法 解决 wregex cout wchar 字符 wcout regexp      更新时间:2023-10-16

我正在处理charwchar_t

我正在编写一个辅助字符串类,该类对某些字符串进行了一些正则表达式(带有 boost),但我既有string又有wstring。现在我有 2 个函数,每个函数都有重复的代码。

int countFoo(const char *s, const char *foo) {
    string text(s);
    boost::regex e(foo);
    int count = 0;
    boost::smatch match;
    while ( boost::regex_search( text, match, e ) ) {
        text = match.suffix();    
        count++;
    }
    return count;
}
int countFoo(const wchar_t *s, const wchar_t *foo) {
    wstring text(s);
    boost::wregex e(foo);
    int count = 0;
    boost::wsmatch match;
    while ( boost::regex_search( text, match, e ) ) {
        text = match.suffix();    
        count++;
    }
    return count;
}

它有效,但我正在寻找一些优雅的方法(模板?一些魔术?函数指针?)来删除重复的代码。

您可以将其编写为模板,如下所示:

template <typename charT>
int countFoo(const charT *s, const charT *foo) {
    basic_string<char> text(s);
    boost::basic_regex<charT> e(foo);
    int count = 0;
    boost::match_results<typename basic_string<charT>::const_iterator> match;
    while ( boost::regex_search( text, match, e ) ) {
        text = match.suffix();    
        count++;
    }
    return count;
}