Search code examples
c++regexstringtemplateswidechar

c++ template and string literals


I want to create template function to parse regular or wide strings. Something like this:

template <class CharT>
bool parseString(std::basic_string<CharT> str)
{
    boost::basic_regex<CharT> myRegex("my_regex_expression");
    boost::match_results<typename std::basic_string<CharT>::const_iterator> what;

    if (boost::regex_search(str, what, filenameRegex) == false)
    {
        return false;
    }

    ...

    return true;
}

template bool parseString<char>(std::string str);
template bool parseString<wchar_t>(std::wstring str);

At this point I'v got problem, in the function I have a predefined string "my_regex_expression". But for a template with wide chars I need a string with wide chars L"my_regex_expression".

How to solve this problem? Create two copy-paste methods for narrow and wide chars? Maybe we have better solution?


Solution

  • It would require a little bit of code duplication but you could have two overloads(one for each type of string) and have them both call a template function that takes the string and the basic_regex. It would be something along the lines of

    template <class String, class Regex>
    bool parseString(const String& str, const Regex & reg)
    {
        boost::match_results<typename String::const_iterator> what;
    
        if (boost::regex_search(str, what, reg) == false)
        {
            return false;
        }
    
        //...
    
        return true;
    }
    
    bool parseString(const std::string& str)
    {
        return parseString(str, boost::basic_regex<char> myRegex("my_regex_expression"));
    }
    
    bool parseString(const std::wstring& str)
    {
        return parseString(str, boost::basic_regex<wchar_t> myRegex(L"my_regex_expression"));
    }