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 ...spa

#ifdef _MBCS
/* ++++++++++++++++++++ MBCS ++++++++++++++++++++ */
#ifdef __cplusplus } /* ... extern "C" */ #endif
#include <mbstring.h>
#ifdef __cplusplus extern "C" { #endifcode

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

#if !__STDC__ typedef char TCHAR; #endifblog

看到了吧,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:string

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++拥有如此强大的能力。

在这里感谢一下Senior Fat Chan的思路

 

更方便的用法:

#ifdef _UNICODE
typedef wstring tstring;
#else typedef string tstring; #endif
相关文章
相关标签/搜索