简体   繁体   中英

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?

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"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM