gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:33:04 26 4
gpt4 key购买 nike

我有一些代码可以读取文件并确定它是否是 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com