c++ - 如何处理可能是 std::string 或 std::wstring 的值

标签 c++ string wstring

我有一些代码可以读取文件并确定它是否是 Unicode。根据这一点,我希望有一个自定义对象,它将文件内容保存为 wstringstring 并能够进行字符串操作。

我想我可以只拥有一个基类,其中包含两个代表宽字符串和窄字符串的派生类,甚至一个用于 string 的基类和一个用于 wstring 的派生类。像这样的东西:

class CustomString
{
public:
   static CustomString *methodFactory(bool _unicode);
   std::string Value;

}

class NarrowString : public CustomString
{
public:
   SingleByte(std::string _value);
   std::string Value;
}

class WideString : public CustomString
{
public:
   WideString (std::wstring _value);
   std::wstring Value
}

我遇到的更多困难是字符串操作方法,比如说我需要 .replace.length.substr 如何我可以实现这些吗?我需要使用模板吗?

virtual T replace(size_t _pos, size_t _len, const T& _str);

或者为每种类型提供两个方法并在派生类中重写它们?

virtual std::string replace(size_t _pos, size_t _len, const std::string& _str)
virtual std::wstring replace(size_t _pos, size_t _len, const std::wstring& _str)

使用模板且不使用继承的界面示例:

class CustomString
{
public:
    CustomString();
    CustomString(bool _unicode);

    template <typename T>
    T get();

    template <typename T>
    T replace(size_t _pos, size_t _len, const T& _str);

    long length();

    template <typename T>
    T substr(size_t _off);

    template <typename T>
    T append(const T& _str);

    template <typename T>
    T c_str();

private:
    std::wstring wValue;
    std::string nValue;
    bool unicode;

};

}

最佳答案

我建议以不同的形式进行:

enum class Encoding{
   UTF8,
   UTF16
};

Encoding readFile(const char* path, std::string& utf8Result,std::wstring& utf16result);

现在将文件读取到正确的对象并返回正确的编码作为结果。 使用此函数可以围绕此函数编写通用代码,并围绕 std::basic_string:

进行模板泛化
template <class T>
void doNext(const std::basic_string<T>& result){/*...*/}

std::string possibleUTF8Result;
std::wstring possibleUTF16Result;
auto res = readFile("text.txt",possibleUTF8Result,possibleUTF16Result);
if (res == Encoding::UTF8){
  doNext(possibleUTF8Result);
} else { doNext(possibleUTF16Result); }

*注意:wstring 在 Windows 上是 utf16,但在 Linux 上是 utf32。

关于c++ - 如何处理可能是 std::string 或 std::wstring 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34923072/

相关文章:

c++ - 自动从一个 sql server 推送到另一个

c++ - 允许函数指针类型的模板参数接受任何返回类型的函数

c - 节点,按值传递,C 中奇怪的字符串行为

java - 比较 LinkedList 中的 int 和 String

c++ - 寻找将 std::wstring 与 NSLog 一起使用的最便宜的方法

C++ SSO:如何以编程方式查找是否使用短字符串优化分配了 std::wstring?

c++ - 线程 C++ 中的瓶颈

python - 从单个 .cpp 构建共享对象

python - 如何查找字符串的开头和结尾

c++ - OS X 上的字符串到 wstring 的转换