我有一些代码可以读取文件并确定它是否是 Unicode。根据这一点,我希望有一个自定义对象,它将文件内容保存为 wstring
或 string
并能够进行字符串操作。
我想我可以只拥有一个基类,其中包含两个代表宽字符串和窄字符串的派生类,甚至一个用于 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/