C++ regex with char and wchar_t?

后端 未结 3 717
余生分开走
余生分开走 2021-01-21 07:23

I have a const char and a const wchar_t. My function below works with the char. What\'s the simplest/most efficient way to write a function that can easily handle both char an

3条回答
  •  日久生厌
    2021-01-21 07:32

    For this reason exactly, regex is a typedef of basic_regex, much like string is a typedef of basic_string. Knowing this, you can get away with a single template:

    template
    std::basic_string
      replaceSubstring(const CharType* find, const CharType* str, const CharType* rep)
    {
        std::basic_string text(str);
        std::basic_regex reg(find);
        return std::regex_replace(text, reg, rep);
    }
    

    This correctly handles both char pointers and wchar_t pointers, and returns the correct type of string. You may want to accept const std::basic_string& parameters instead, too.

提交回复
热议问题