2016-01-21 47 views
1

我有一些代码读取文件并找出它是否是Unicode。根据这个我想有一个自定义对象,将文件内容保存为wstringstring并且能够进行字符串操作。如何处理一个值可能是一个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; 

}; 

}

+0

你需要使用模板 –

+0

我不会写新类。我会写通用代码。那就是你不在乎你是否有字符串或者字符串。你所关心的只是你可以在你的物体上进行的操作。两个类都支持相同的操作。 – bolov

+3

为什么不总是将内容作为wstring加上一个标志来说明原始文件是否是Unicode? –

回答

1

我建议做它在不同的形式:

enum class Encoding{ 
    UTF8, 
    UTF16 
}; 

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

现在将文件读取到正确的对象并返回正确的编码作为结果。 使用此功能可以写周围的模板generelization此功能的通用代码周围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的是UTF-16上的窗户,但UTF32在Linux上。

相关问题