1
我有一些代码读取文件并找出它是否是Unicode。根据这个我想有一个自定义对象,将文件内容保存为wstring
或string
并且能够进行字符串操作。如何处理一个值可能是一个std :: string或std :: wstring
我想我可以只有一个基类,它有两个派生类,分别表示宽和窄字符串,或者甚至是基类,用于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;
};
}
你需要使用模板 –
我不会写新类。我会写通用代码。那就是你不在乎你是否有字符串或者字符串。你所关心的只是你可以在你的物体上进行的操作。两个类都支持相同的操作。 – bolov
为什么不总是将内容作为wstring加上一个标志来说明原始文件是否是Unicode? –