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
相關文章
相關標籤/搜索