STL的string和wstring

STL有字符串处理类——stirng和wstring,但是用的时候会觉得不是很方便,因为它不能像TCHAR一样根据定义的宏在char类型字符串和wchar_t进行转换,总不能因为程序要Unicode就把所有类型转换一遍吧?有没有好办法?

答案当然是肯定的,先看看MS的TCHAR是怎么做的,以下摘自MS Platform 的tchar.h,略有删减

#ifdef _UNICODE

#ifdef __cplusplus
} /* ... extern "C" */
#endif

/* ++++++++++++++++++++ UNICODE ++++++++++++++++++++ */

#include <wchar.h>

#ifdef __cplusplus
extern "C" {
#endif

#if !__STDC__
typedef wchar_t TCHAR;
#endif
...

#ifdef _MBCS

/* ++++++++++++++++++++ MBCS ++++++++++++++++++++ */

#ifdef __cplusplus
} /* ... extern "C" */
#endif

#include <mbstring.h>

#ifdef __cplusplus
extern "C" {
#endif

#ifndef __TCHAR_DEFINED
typedef char _TCHAR;
typedef signed char _TSCHAR;

#if !__STDC__
typedef char TCHAR;
#endif

看到了吧,TCHAR就是根据_MBCS和_UNICODE宏来作为char和wchar_t的typedef。

下面再看看string和wstring两个类:

typedef basic_string<char, char_traits<char>, allocator<char> >
 string;
typedef basic_string<wchar_t, char_traits<wchar_t>,
 allocator<wchar_t> > wstring;
原来string和wstring也是个typedef,都是模板basic_string的具现,既然只是个模板具现,那么其实现是不依赖于具体类型的,这也就是模板的意义——把实现从具体类型中抽象出来。

那么我们可以自己做个tstring:

typedef basic_string<TCHAR, char_traits<TCHAR>,
 allocator<TCHAR> > tstring;

这样tstring就可以根据宏的不同而成为string或wstring,用的时候只需要定义需要的宏,不用大面积修改代码了。

模板赋予了STL强大的功能,一个通用的库肯定不能包容所有需要,但是良好的库应该有良好的扩展性,像string、wstring,既然不能满足日常开发中灵活的转换,那么我们就自己动手,具现一个tstring,stirng中所有的成员函数、算法都不用实现,除非你有特殊需要,因为模板已经将这些函数、算法都实现好了,我们要做的只需要具现就好了。

其实不止string和wstring,fstream和wfstream也可以像string和wstring一样,通过basic_fstream模板具现一个tfstream

这就是模板强大的威力,也只有C++拥有如此强大的能力。

原文地址:https://www.cnblogs.com/lidabo/p/3564419.html