2

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?

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Victor Mezrin
  • 2,797
  • 2
  • 32
  • 48
  • Possible duplicate of [templates and string literals and UNICODE](https://stackoverflow.com/questions/4261673/templates-and-string-literals-and-unicode) – dimm Mar 13 '18 at 11:30

1 Answers1

3

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"));
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • Is it the only solution? I am stuck into the same problem and I do not want to duplicate a bunch of functions like that… – Boiethios Mar 13 '17 at 21:28